는 Kubernetes 시리즈 둘째 : kubectl 명령는 Kubernetes를 사용하는 응용 프로그램을 만들

1. 소개

이 인터페이스는 K8S 통해 클러스터에 사용자가 요청을 시작 할 수는 API 서버는 편안한 스타일의 게이트웨이 인터페이스를 제공 K8S. 포드는 포드 다른 작업을 만들거나 파괴로
사용자 또는 대시 보드로를 통해 명령과 kubectl의 K8S 자신의 API 서버를 통해 통신 할 수있다, 통신 및 프로그래밍 언어가 제공하는 API 서버 API 서버 게이트웨이 인터페이스 규격을 따를 수 웹 UI 및 API 서버가 통신 할 수
kubectl CLI 도구 및 공식 통신을위한 API 서버이며, 가장 일반적으로 사용되는 대화 형 명령 줄 도구 인

2. kubectl

2.1.보기 명령 도움말

# 查看 kubectl 命令帮助
[root@master ~]# kubectl --help
# 基础命令(适合初学者使用)
Basic Commands (Beginner):
  create         创建资源, k8s 支持从 yaml 文件或者命令行参数直接创建资源
  expose         暴露服务
  run            运行 Pod 
  set            设置对象属性

# 基础命令
Basic Commands (Intermediate):
  explain        
  get            获取资源信息
  edit           编辑资源
  delete         删除资源

# 部署命令
Deploy Commands:
  rollout        更新管理
  scale          手动管理副本
  autoscale      自动管理副本

# 集群管理命令
Cluster Management Commands:
  certificate    证书管理
  cluster-info   查看集群信息
  top            显示资源(CPU/内存/存储)使用情况
  cordon         将指定 node 设定为"不可用"(unschedulable)状态
  uncordon       将指定 node 设定为"可用"(schedulable)状态
  drain          排空节点
  taint          为 node 声明污点及标准行为

# 故障排除和调试命令
Troubleshooting and Debugging Commands:
  describe       显示特定资源或资源组的详细信息
  logs           打印 Pod 中的容器日志
  attach         连接到正在运行的容器
  exec           在容器中执行命令
  port-forward   将一个或多个本地端口转发到 Pod 中
  proxy          运行 k8s API Server 代理
  cp             跨容器之间复制文件或目录
  auth           检查授权

# 高级命令
Advanced Commands:
  apply          基于文件或 stdin 将配置应用于资源
  patch          使用策略合并补丁更新资源字段
  replace        基于文件或 stdin 替换一个资源
  wait           目前处于测试阶段, 在一个或多个资源上等待一个条件
  convert        为不同的 API 版本转换配置文件

# 资源设置
Settings Commands:
  label          更新资源上的标签(label)
  annotate       更新资源的a nnotation
  completion     输出指定的 shell 的补全码

# 其他命令
Other Commands:
  alpha          Commands for features in alpha
  api-resources  在服务器上打印支持的 API 资源
  api-versions   以 "group/version" 格式打印服务器支持的 API 版本信息
  config         修改 kubeconfig 文件
  plugin         运行命令行插件
  version        查看 k8s 版本

# 使用格式
Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

포드를 실행 kubectl 2.2 사용

# 运行一个由 deployment 管理器管理的 pod
[root@master ~]# kubectl run nginx --image=nginx:1.14-alpine --replicas=5
deployment.apps/nginx created

# 查看 pod
[root@master ~]# kubectl get pod -o wide
NAME                     READY     STATUS    RESTARTS   AGE       IP           NODE
nginx-65759d8bcb-96kgd   1/1       Running   0          7s       10.244.3.6   node02
nginx-65759d8bcb-97dch   1/1       Running   0          7s       10.244.1.5   node01
nginx-65759d8bcb-mzzwh   1/1       Running   0          8s       10.244.1.4   node01
nginx-65759d8bcb-vxs74   1/1       Running   0          8s       10.244.3.5   node02
nginx-65759d8bcb-z6d4r   1/1       Running   0          8s       10.244.3.4   node02

NAME        Pod 名称
READY       这个 Pod 内应该运行几个容器/已经准备好几个容器
STATUS      运行状态
RESTARTS    Pod 重启次数
AGE         已存在多长时间, 单位秒(s)
IP          Pod IP(这个地址只能在集群内部使用, 且 Pod IP 随时都会发生改变)
NODE        运行节点

# 查看 deployment 管理器
[root@master ~]# kubectl get deployment
NAME      DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx     5         5         5            5           18s

NAME            deployment 管理器名称
DESIRED         期望有多少个副本
CURRENT         当前有多少个副本
UP-TO-DATE      处于最新状态的 Pod 数量
AVAILABLE       活跃的 Pod 数量
AGE             已存在多长时间, 单位秒(s)

# 在集群内部访问 Pod
[root@master ~]# curl 10.244.1.5
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

2.3. 서비스를 사용하여 서비스를 드러내 기

포드 클라이언트는 두 가지 범주로 나누어, 集群外客户端그리고 集群内客户端. 고객은 직접 포드 포드 IP 접속을 통해 클러스터 및 클러스터 외부 클라이언트 내의 모든 액세스는 우리가 단지 클러스터 내에서 직접 포드 IP 액세스를 사용할 수 없습니다 경우에도 언제든지 변경 될 수 있습니다 포드 IP 및 포드 IP에 액세스 할 수 없습니다 수
및 서비스를 주로 고정 된 서비스 액세스 인터페이스와 서비스 액세스가 자동으로 포드의 백엔드 클라이언트 브라우저에 배포되는이 서비스에 관련된 포드 바인딩을 제공하는 서비스를 만들어이 두 가지 문제가 존재 해결하기 위해
CoreDNS K8S가 설치 한 경우, 당신은 DNS를 할당 할 수있는 서비스가 내부 레코드를 업데이트합니다 CoreDNS DNS 확인 레코드의 효율성을 보장하기 위해 해결하기 위해 변경하는 경우 CoreDNS 모든 포드가입니다입니다

# 创建 service
[root@master ~]# kubectl expose deployment nginx --name=nginx-service --port=80 --target-port=80 --protocol=TCP --type=ClusterIP
service/nginx-service exposed

kubectl expose          创建 service 关键字
deployment nginx        绑定的 Pod 管理器(将会暴露此 Pod 管理器所管理的所有 Pod)
--name                  指定 service 的名称
--port                  暴露的端口
--target-port           目标端口
--protocol              暴露的协议(默认为 TCP)
--type                  service 类型, ClusterIP 为集群 IP, 此类型的 service 在集群外部也不能被访问

# 查看已存在的 service
[root@master ~]# kubectl get service
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP   6d
nginx-service   ClusterIP   10.107.73.166   <none>        80/TCP    33s

# 查看 service 的详细信息
[root@master ~]# kubectl describe service nginx-service
Name:              nginx-service
Namespace:         default
Labels:            run=nginx
Annotations:       <none>
# 关联标签 run 且 run 为 nginx 的所有 pod(通过此项完成 pod 和 service 的绑定)
Selector:          run=nginx
Type:              ClusterIP
IP:                10.107.73.166
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.4:80,10.244.1.5:80,10.244.3.4:80 + 2 more...
Session Affinity:  None
Events:            <none>

# 显示各 pod 的 label
[root@master ~]# kubectl get pod --show-labels      
NAME                     READY     STATUS    RESTARTS   AGE       LABELS
client                   1/1       Running   0          54m       run=client
nginx-65759d8bcb-96kgd   1/1       Running   0          5h        pod-template-hash=2131584676,run=nginx
nginx-65759d8bcb-97dch   1/1       Running   0          5h        pod-template-hash=2131584676,run=nginx
nginx-65759d8bcb-mzzwh   1/1       Running   0          5h        pod-template-hash=2131584676,run=nginx
nginx-65759d8bcb-vxs74   1/1       Running   0          5h        pod-template-hash=2131584676,run=nginx
nginx-65759d8bcb-z6d4r   1/1       Running   0          5h        pod-template-hash=2131584676,run=nginx

# 使用 service ip 访问 Pod
[root@master ~]# curl 10.107.73.166
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

포드에 액세스 할 수 2.4을 사용하여 DNS 이름

# 查看 kube-dns(真实使用的为 CoreDNS) 的 service 地址
[root@master ~]# kubectl get service -n kube-system
NAME       TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)         AGE
kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP   7d

[root@master ~]# kubectl get service
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP   7d
nginx-service   ClusterIP   10.107.73.166   <none>        80/TCP    46m

# 使用 CoreDNS 解析主机名, nginx-service 为 service 名称, default.svc.cluster.local 为 DNS 后缀
[root@master ~]# dig -t A nginx-service.default.svc.cluster.local @10.96.0.10
......
# 解析结果
nginx-service.default.svc.cluster.local. 5 IN A 10.107.73.166

;; Query time: 7 msec
;; SERVER: 10.96.0.10#53(10.96.0.10)
;; WHEN: Thu Feb 28 16:36:29 CST 2019
;; MSG SIZE  rcvd: 123

# 建立一个客户端 Pod
[root@master ~]# kubectl run client --image=busybox -it --restart=Never

# 在 Pod 内部使用 service 名称访问
/ # wget -O - -q nginx-service
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

2.5. 동적으로 복사 포드의 번호를 수정

# 将副本数量修改为 2
[root@master ~]# kubectl scale --replicas=2 deployment nginx
deployment.extensions/nginx scaled

# 查看 nginx 控制器的详细信息
[root@master ~]# kubectl describe deployment nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Thu, 28 Feb 2019 12:05:59 +0800
Labels:                 run=nginx
Annotations:            deployment.kubernetes.io/revision=1
Selector:               run=nginx
# 副本详细信息
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=nginx
  Containers:
   nginx:
    Image:        nginx:1.14-alpine
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-65759d8bcb (2/2 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  1m    deployment-controller  Scaled down replica set nginx-65759d8bcb to 2

2.6 업데이트

# 查看当前 Pod 的详细信息
[root@master ~]# kubectl describe pod nginx-65759d8bcb-97dch
Name:               nginx-65759d8bcb-97dch
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               node01/192.168.1.51
Start Time:         Thu, 28 Feb 2019 12:06:00 +0800
Labels:             pod-template-hash=2131584676
                    run=nginx
Annotations:        <none>
Status:             Running
IP:                 10.244.1.5
Controlled By:      ReplicaSet/nginx-65759d8bcb
# pod 内运行的容器
Containers:
  # 容器名称
  nginx:
    Container ID:   docker://2a97be8c74ac715569b4cbd542cb1df0b52f49cd1ee89f1d7bdf15464678d274
    # 容器镜像
    Image:          nginx:1.14-alpine
    Image ID:       docker-pullable://nginx@sha256:b96aeeb1687703c49096f4969358d44f8520b671da94848309a3ba5be5b4c632
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Thu, 28 Feb 2019 12:06:01 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-t9pnn (ro)
# pod 内运行的第二个容器, 这儿只有一个容器
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-t9pnn:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-t9pnn
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>

# 更新镜像版本
[root@master ~]# kubectl set image deployment nginx nginx=nginx:alpine
deployment.extensions/nginx image updated

kubectl set image       更新进行关键字
deployment nginx        nginx deployment 控制器
nginx                   pod 内的容器名称(更新时只能指定更新容器)
nginx:alpine            镜像版本

# 查看更新过程
[root@master ~]# kubectl rollout status deployment nginx
Waiting for deployment "nginx" rollout to finish: 1 out of 2 new replicas have been updated...
Waiting for deployment "nginx" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "nginx" rollout to finish: 1 old replicas are pending termination...
deployment "nginx" successfully rolled out

# 查看更新完成后的 pod
[root@master ~]# kubectl get pod
NAME                     READY     STATUS    RESTARTS   AGE
client                   1/1       Running   0          1h
nginx-5557945897-87st5   1/1       Running   0          1m
nginx-5557945897-zgggq   1/1       Running   0          1m

# 查看 pod 详细信息
[root@master ~]# kubectl describe pod nginx-5557945897-87st5
Name:               nginx-5557945897-87st5
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               node02/192.168.1.52
Start Time:         Thu, 28 Feb 2019 17:52:21 +0800
Labels:             pod-template-hash=1113501453
                    run=nginx
Annotations:        <none>
Status:             Running
IP:                 10.244.3.8
Controlled By:      ReplicaSet/nginx-5557945897
Containers:
  nginx:
    Container ID:   docker://fcb8166d53a6c2c6392bc14f80cd9161caf13e3e26cad433ed0d9da133b41c6b
    Image:          nginx:alpine
    Image ID:       docker-pullable://nginx@sha256:0f7920c93d6b60f3e13c1b847f1863f423c3149d06e53475e64560933d168adc
    ......

2.7. 롤백

# 回滚到指定版本, 默认回滚到上一个版本
[root@master ~]# kubectl rollout undo deployment nginx
deployment.extensions/nginx

kubectl rollout undo    关键字
deployment nginx        控制器
--to-revision           指定回滚到那个版本

[root@master ~]# kubectl get pod
NAME                     READY     STATUS    RESTARTS   AGE
client                   1/1       Running   0          1h
nginx-65759d8bcb-gm4sj   1/1       Running   0          1m
nginx-65759d8bcb-n2222   1/1       Running   0          1m

# 查看回滚后的 pod 信息
[root@master ~]# kubectl describe deployment nginx nginx-65759d8bcb-gm4sj
Name:                   nginx
Namespace:              default
CreationTimestamp:      Thu, 28 Feb 2019 12:05:59 +0800
Labels:                 run=nginx
Annotations:            deployment.kubernetes.io/revision=5
Selector:               run=nginx
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=nginx
  Containers:
   nginx:
    Image:        nginx:1.14-alpine
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>

2.8. 출시는 클러스터 외부 서비스에

# 新创建一个 service, service 的 NodePort 模式允许外部流量访问 k8s 集群
[root@master ~]# kubectl expose deployment nginx --name=nginx-service-internet --port=80 --type=NodePort
service/nginx-service-internet exposed

# 在外部访问 k8s 任意节点的 32081 即可访问 nginx pod
[root@master ~]# kubectl get service
NAME                     TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes               ClusterIP   10.96.0.1        <none>        443/TCP        7d
nginx-service            ClusterIP   10.107.73.166    <none>        80/TCP         18h
nginx-service-internet   NodePort    10.107.217.105   <none>        80:32081/TCP   11s

# 或者修改现有 service 的 type 将其发布到集群外部
[root@master ~]# kubectl edit service nginx-service
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: 2019-02-28T07:50:21Z
  labels:
    run: nginx
  name: nginx-service
  namespace: default
  resourceVersion: "474911"
  selfLink: /api/v1/namespaces/default/services/nginx-service
  uid: 7f7ef303-3b2d-11e9-9b82-000c292a04ff
spec:
  clusterIP: 10.107.73.166
  externalTrafficPolicy: Cluster
  ports:
  - nodePort: 31987
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    run: nginx
  sessionAffinity: None
  # 修改为 NodePort
  type: NodePort
status:
  loadBalancer: {}

# 现在访问任意节点的 31987 和 32081 都能够访问到后端 pod 资源
[root@master ~]# kubectl get service               
NAME                     TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes               ClusterIP   10.96.0.1        <none>        443/TCP        7d
nginx-service            NodePort    10.107.73.166    <none>        80:31987/TCP   18h
nginx-service-internet   NodePort    10.107.217.105   <none>        80:32081/TCP   3m

추천

출처blog.51cto.com/hongchen99/2440338