一、概述

  • Kubectl是管理k8s集群的命令行工具,通过生成的json格式传递给apiserver进行创建、查看、管理的操作。
  • 对于kubectl命令,我们可以使用kubectl --help来看下帮助手册,查看相关参数的使用
[root@k8s_master ~]# kubectl --help
kubectl controls the Kubernetes cluster manager. 

Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
  create         Create a resource from a file or from stdin.
  expose         使用 replication controller, service, deployment 或者 pod
并暴露它作为一个 新的 Kubernetes Service
  run            在集群中运行一个指定的镜像
  set            为 objects 设置一个指定的特征

Basic Commands (Intermediate):
  explain        查看资源的文档
  get            显示一个或更多 resources
  edit           在服务器上编辑一个资源
  delete         Delete resources by filenames, stdin, resources and names, or by resources and
label selector

Deploy Commands:
  rollout        Manage the rollout of a resource
  scale          为 Deployment, ReplicaSet, Replication Controller 或者 Job
设置一个新的副本数量
  autoscale      自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController
的副本数量

Cluster Management Commands:
  certificate    修改 certificate 资源.
  cluster-info   显示集群信息
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         标记 node 为 unschedulable
  uncordon       标记 node 为 schedulable
  drain          Drain node in preparation for maintenance
  taint          更新一个或者多个 node 上的 taints

Troubleshooting and Debugging Commands:
  describe       显示一个指定 resource 或者 group 的 resources 详情
  logs           输出容器在 pod 中的日志
  attach         Attach 到一个运行中的 container
  exec           在一个 container 中执行一个命令
  port-forward   Forward one or more local ports to a pod
  proxy          运行一个 proxy 到 Kubernetes API server
  cp             复制 files 和 directories 到 containers 和从容器中复制 files 和
directories.
  auth           Inspect authorization

Advanced Commands:
  apply          通过文件名或标准输入流(stdin)对资源进行配置
  patch          使用 strategic merge patch 更新一个资源的 field(s)
  replace        通过 filename 或者 stdin替换一个资源
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        在不同的 API versions 转换配置文件

Settings Commands:
  label          更新在这个资源上的 labels
  annotate       更新一个资源的注解
  completion     Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  alpha          Commands for features in alpha
  api-resources  Print the supported API resources on the server
  api-versions   Print the supported API versions on the server, in the form of "group/version"
  config         修改 kubeconfig 文件
  plugin         Provides utilities for interacting with plugins.
  version        输出 client 和 server 的版本信息

二、kubectl命令的使用

以项目的生命周期的形式进行述说,创建–》发布–》更新–》回滚–》删除

1、pod创建
  • kubectl run 命令
  • 格式:
    kubectl run NAME --image=image --port=port --replicas=replicas --dry-run=bool --overrides=inline-json args…
  • 示例:
##创建nginx的pod,端口为80,副本数为3
[root@k8s_master ~]# kubectl run nginx-abc --image=nginx --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx-abc created

##-w参数动态的监控创建过程
[root@k8s_master ~]# kubectl get pods -w
NAME                        READY   STATUS    RESTARTS   AGE
nginx-abc-8c8f9d6bf-9q5zq   1/1     Running   0          16s
nginx-abc-8c8f9d6bf-dlz62   1/1     Running   0          16s
nginx-abc-8c8f9d6bf-l642g   1/1     Running   0          16s

##查看已经创建的pods
[root@k8s_master ~]# kubectl get pods 
NAME                        READY   STATUS    RESTARTS   AGE
nginx-abc-8c8f9d6bf-9q5zq   1/1     Running   0          85s
nginx-abc-8c8f9d6bf-dlz62   1/1     Running   0          85s
nginx-abc-8c8f9d6bf-l642g   1/1     Running   0          85s

##查看pod分配到哪个节点
[root@k8s_master ~]# kubectl get pods -o wide
NAME                        READY   STATUS    RESTARTS   AGE    IP            NODE           NOMINATED NODE
nginx-abc-8c8f9d6bf-9q5zq   1/1     Running   0          2m4s   172.17.93.2   192.168.5.30   <none>
nginx-abc-8c8f9d6bf-dlz62   1/1     Running   0          2m4s   172.17.56.2   192.168.5.20   <none>
nginx-abc-8c8f9d6bf-l642g   1/1     Running   0          2m4s   172.17.56.4   192.168.5.20   <none>
  • kubectl create 命令也可以创建pod
  • 格式:
kubectl create -f  <指定yaml文件>
2、pod发布
  • kubectl expose命令
  • 格式:
    kubectl expose (-f FILENAME | TYPE NAME) --port=port --protocol=TCP|UDP|SCTP --target-port=number-or-name --name=name --external-ip=external-ip-of-service --type=type
  • 示例:
##发布nginx
[root@k8s_master ~]# kubectl expose deployment nginx-abc --port=80 --target-port=80 --name=nginx-service --type=NodePort 
service/nginx-service exposed

##查看服务
[root@k8s_master ~]# kubectl get service
NAME            TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
nginx-service   NodePort    10.0.0.46    <none>        80:42862/TCP   67s

##查看nginx服务关联节点,对应上面的pod分配情况
[root@k8s_master ~]# kubectl get endpoints
NAME            ENDPOINTS                                      AGE
nginx-service   172.17.56.2:80,172.17.93.2:80,172.17.93.3:80   4m52s

  • 使用对外端口42862访问

在这里插入图片描述

  • 查看访问日志
##查看pod获取pod id信息
[root@k8s_master ~]# kubectl get pods
NAME                        READY   STATUS    RESTARTS   AGE
nginx-abc-8c8f9d6bf-9nsbx   1/1     Running   0          15m
nginx-abc-8c8f9d6bf-nqrzf   1/1     Running   0          15m
nginx-abc-8c8f9d6bf-r2776   1/1     Running   0          15m

##查看日志信息
[root@k8s_master ~]# kubectl logs nginx-abc-8c8f9d6bf-9nsbx
172.17.56.1 - - [09/May/2020:16:17:52 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36" "-"
2020/05/09 16:17:52 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.56.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.5.20:42862", referrer: "http://192.168.5.20:42862/"
3、更新版本
  • kubectl set命令
  • 详细参数
[root@k8s_master ~]#  kubectl set  --help
Configure application resources 

These commands help you make changes to existing application resources.

Available Commands:
  env            Update environment variables on a pod template
  image          更新一个 pod template 的镜像
  resources      在对象的 pod templates 上更新资源的 requests/limits
  selector       设置 resource 的 selector
  serviceaccount Update ServiceAccount of a resource
  subject        Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding

  • 执行更新
[root@k8s_master ~]# kubectl set image deployment/nginx-abc  nginx-abc=nginx:1.14
deployment.extensions/nginx-abc image updated

##监控更新情况
[root@k8s_master ~]# kubectl get pods -w
NAME                         READY   STATUS    RESTARTS   AGE
nginx-abc-85f9cb7f9f-78kpr   1/1     Running   0          51s
nginx-abc-85f9cb7f9f-bbfkm   1/1     Running   0          38s
nginx-abc-85f9cb7f9f-pxltd   1/1     Running   0          27s
  • 再次访问nginx资源,验证更新情况

在这里插入图片描述

4、回滚
  • kubectl rollout命令
  • 详细参数
[root@k8s_master ~]#  kubectl rollout --help
Manage the rollout of a resource.
  
Valid resource types include: 

  * deployments  
  * daemonsets  
  * statefulsets

Examples:
  # Rollback to the previous deployment
  kubectl rollout undo deployment/abc
  
  # Check the rollout status of a daemonset
  kubectl rollout status daemonset/foo

Available Commands:
  history     显示 rollout 历史
  pause       标记提供的 resource 为中止状态
  resume      继续一个停止的 resource
  status      显示 rollout 的状态
  undo        撤销上一次的 rollout

  • 执行回滚操作(回滚到上一次状态)
##查看历史状态版本
[root@k8s_master ~]#  kubectl rollout history deployment/nginx-abc
deployment.extensions/nginx-abc 
REVISION  CHANGE-CAUSE
1         <none>       ##对应第一次创建服务
2         <none>       ##对应进行更新后的状态

##执行回滚
[root@k8s_master ~]# kubectl rollout undo deployment/nginx-abc
deployment.extensions/nginx-abc

##查看回滚状态
[root@k8s_master ~]#  kubectl rollout status deployment/nginx-abc
Waiting for deployment "nginx-abc" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "nginx-abc" rollout to finish: 1 old replicas are pending termination...
deployment "nginx-abc" successfully rolled out
  • 验证回滚操作

在这里插入图片描述

5、查看资源的详细信息(可以看到该资源日志信息)

信息的最后Events字段是pod的日志信息

  • kubectl describe命令
##获取pod id信息
[root@k8s_master ~]#  kubectl get pods
NAME                        READY   STATUS    RESTARTS   AGE
nginx-abc-8c8f9d6bf-bgqlx   1/1     Running   0          13m
nginx-abc-8c8f9d6bf-rml88   1/1     Running   0          14m
nginx-abc-8c8f9d6bf-txx94   1/1     Running   0          14m

##查看pod详细信息
[root@k8s_master ~]# kubectl describe pod nginx-abc-8c8f9d6bf-bgqlx
Name:               nginx-abc-8c8f9d6bf-bgqlx
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               192.168.5.30/192.168.5.30
Start Time:         Sun, 10 May 2020 00:38:21 +0800
Labels:             pod-template-hash=8c8f9d6bf
                    run=nginx-abc
Annotations:        <none>
Status:             Running
IP:                 172.17.93.3
Controlled By:      ReplicaSet/nginx-abc-8c8f9d6bf
Containers:
  nginx-abc:
    Container ID:   docker://8197f85b7b10569afd54580b0684d664183bca55d136d43421bf2d823a327a83
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:86ae264c3f4acb99b2dee4d0098c40cb8c46dcf9e1148f05d3a51c4df6758c12
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sun, 10 May 2020 00:38:28 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-ntvcb (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-ntvcb:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-ntvcb
    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:
  Type    Reason     Age   From                   Message
  ----    ------     ----  ----                   -------
  Normal  Scheduled  11m   default-scheduler      Successfully assigned default/nginx-abc-8c8f9d6bf-bgqlx to 192.168.5.30
  Normal  Pulling    11m   kubelet, 192.168.5.30  pulling image "nginx"
  Normal  Pulled     11m   kubelet, 192.168.5.30  Successfully pulled image "nginx"
  Normal  Created    11m   kubelet, 192.168.5.30  Created container
  Normal  Started    11m   kubelet, 192.168.5.30  Started container
6、进入pod
  • 命令: kubectl exec
[root@k8s_master ~]#  kubectl exec -it nginx-abc-8c8f9d6bf-bgqlx bash
root@nginx-abc-8c8f9d6bf-bgqlx:/# ls 
bin  boot  dev	etc  home  lib	lib64  media  mnt  opt	proc  root  run  sbin  srv  sys  tmp  usr  var
7、删除pod资源(删除控制器和nginx服务)
##显示资源和服务
[root@k8s_master ~]# kubectl get deploy,service
NAME                              DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.extensions/nginx-abc   3         3         3            3           49m

NAME                    TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
service/kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        10d
service/nginx-service   NodePort    10.0.0.46    <none>        80:42862/TCP   43m

##执行删除
[root@k8s_master ~]# kubectl delete deployment/nginx-abc 
deployment.extensions "nginx-abc" deleted

[root@k8s_master ~]# kubectl delete service/nginx-service
service "nginx-service" deleted

##验证
[root@k8s_master ~]# kubectl get pods
No resources found.
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐