1、实验概述

使用Kubectl 命令行工具操作 kubernetes 集群是最直接的管理集群的途径。开始实验后,系统自动在阿里云上创建一个Kubernetes集群。根据实验步骤操作说明,远程登陆集群master节点,然后使用kubectl命令行工具,对集群进行基本操作。包括创建资源对象,显示和查找资源对象,更新资源对象,伸缩资源对象,删除资源对象,执行容器命令,查看容器日志等。

2、实验目的

熟悉Kubernetes集群的命令行工具kubectl的基本使用方法,熟悉常用的kubectl命令。


3、实验架构

本次实验中,首先基于阿里云容器服务Kubernetes版,创建一个Kubernetes集群。集群由3个主节点和1个工作节点组成。

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_vim


实验实施

实验资源

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_02

输入资源提供的“子用户名称”和“子用户密码”登录。

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_03

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_04

2. 进入 容器服务 产品的控制台

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_命令行工具_05

进入 集群

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_命令行工具_06

3 获取Master节点SSH连接地址。

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_07

4 登录用户名为root,密码见实验资源。下一节通过 Master节点SSH连接地址,用户名和密码远程登录。

2.1 远程连接Kubernetes集群的master节点

在本机上使用PuTTy或其他远程连接工具,连接到本实验创建的Kubernetes集群的master远程连接地址。结果如下:

[root@iZuf6hwg7vmzj9zlz627l6Z ~]# ssh root@47.103.32.162
The authenticity of host '47.103.32.162 (47.103.32.162)' can't be established.
ECDSA key fingerprint is SHA256:Nh2uvZKQIk3Aiycsz8gqGs2ZMPNXe/lueGV5Ak/RHIw.
ECDSA key fingerprint is MD5:1d:8c:51:30:52:fb:b1:32:02:ae:86:cc:83:fa:8c:51.
Are you sure you want to continue connecting (yes/no)? yes
[root@iZuf6hwg7vmzj9zlz627l6Z ~]#
[root@iZuf6hwg7vmzj9zlz627l6Z ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_08

登陆成功后,执行命令kubectl查看命令行工具kubectl的使用说明。结果如下:

[root@LYX ~]# kubectl

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          Take a replication controller, service, deployment or pod and expose it as a new Kubernetes service
  run             Run a particular image on the cluster
  set             Set specific features on objects

Basic Commands (Intermediate):
  explain         Get documentation for a resource
  get             Display one or many resources
  edit            Edit a resource on the server
  delete          Delete resources by file names, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout         Manage the rollout of a resource
  scale           Set a new size for a deployment, replica set, or replication controller
  autoscale       Auto-scale a deployment, replica set, stateful set, or replication controller

Cluster Management Commands:
  certificate     Modify certificate resources.
  cluster-info    Display cluster information
  top             Display resource (CPU/memory) usage
  cordon          Mark node as unschedulable
  uncordon        Mark node as schedulable
  drain           Drain node in preparation for maintenance
  taint           Update the taints on one or more nodes
。。。。。。。。。。。。。

查看具体子命令的详细用法。例如,执行命令,kubectl create --help,查看create命令的详细用法。结果如下:

[root@LYX ~]# kubectl create --help

Create a resource from a file or from stdin.

 JSON and YAML formats are accepted.

Examples:
  # Create a pod using the data in pod.json
  kubectl create -f ./pod.json

  # Create a pod based on the JSON passed into stdin
  cat pod.json | kubectl create -f -

  # Edit the data in registry.yaml in JSON then create the resource using the edited data
  kubectl create -f registry.yaml --edit -o json

Available Commands:
  clusterrole           Create a cluster role
  clusterrolebinding    Create a cluster role binding for a particular cluster role
  configmap             Create a config map from a local file, directory or literal value
  cronjob               Create a cron job with the specified name
  deployment            Create a deployment with the specified name
  ingress               Create an ingress with the specified name
  job                   Create a job with the specified name
  namespace             Create a namespace with the specified name
  poddisruptionbudget   Create a pod disruption budget with the specified name
  priorityclass         Create a priority class with the specified name
  quota                 Create a quota with the specified name
  role                  Create a role with single rule
  rolebinding           Create a role binding for a particular role or cluster role
  secret                Create a secret using specified subcommand
  service               Create a service using a specified subcommand
  serviceaccount        Create a service account with the specified name
  token                 Request a service account token

2.2 使用kubectl创建资源对象

1. 直接部署nginx应用

编辑用于部署nginx应用的yaml文件(YAML是一个类似 XML、JSON 的标记性语言。yaml能直观地被电脑识别,是一种可读性高、容易被人类阅读、容易和脚本语言交互的编程语言)。

执行命令vim deployment-nginx.yaml,输入文件内容。按“i”键进入编辑模式,对默认首页文件进行修改;修改完成后按“Esc”键退出编辑模式,然后输入组合键“:wq”保存文件并退出。结果如下所示:

[root@LYX ~]# vim deployment-nginx.yaml
 
[root@LYX ~]# cat deployment-nginx.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7
        ports:
        - containerPort: 80
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_09

文本说明:此yaml文件用于部署基础nginx应用,副本数量为2,应用使用的镜像和版本为nginx:1.7,开放的容器端口为80。

使用命令行工具kubectl创建资源对象deployment。在当前目录下,执行命令kubectl create -f deployment-nginx.yaml,即可基于刚才添加的配置文件deployment-nginx.yaml,创建资源对象depolyment。结果如下:

[root@LYX ~]# kubectl create -f deployment-nginx.yaml

deployment.apps/nginx-deployment created
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_10

2. 通过创建副本控制器(RC)部署nginx应用

编辑用于创建nginx应用的副本控制器的yaml文件,执行命令vim controller-nginx.yaml,输入文件内容,结果如下所示:

[root@LYX ~]# vim controller-nginx.yaml
 
[root@LYX ~]# cat controller-nginx.yaml
apiVersion: v1
kind: ReplicationController
metadata:
   name: nginx-controller
   labels:
     name: nginx-controller
spec:
  replicas: 1
  selector:
     name: nginx-controller
  template:
    metadata:
     labels:
       name: nginx-controller
    spec:
      containers:
      - name: nginx-controller
        image: nginx:1.9
        ports:
        - containerPort: 8000
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_nginx_11

文本说明:此yaml文件用于部署副本控制器RC,副本数量为1,应用使用的镜像和版本为nginx:1.9,开放的容器端口为8000。

使用命令行工具kubectl创建资源对象Replication Controller。在当前目录下,执行命令kubectl create -f controller-nginx.yaml,即可基于刚才添加的配置文件controller-nginx.yaml,创建资源对象Replication Controller。结果如下:

[root@LYX ~]# kubectl create -f controller-nginx.yaml

replicationcontroller/nginx-controller created
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_vim_12

2.3 使用kubectl显示和查找资源对象

查看节点列表。执行命令kubectl get nodes,查看集群中节点列表,结果如下:

[root@LYX ~]# kubectl get nodes

NAME                       STATUS   ROLES           AGE   VERSION
cn-shanghai.172.16.1.104   Ready    control-plane   26m   v1.24.6-aliyun.1
cn-shanghai.172.16.1.105   Ready    control-plane   24m   v1.24.6-aliyun.1
cn-shanghai.172.16.1.106   Ready    control-plane   22m   v1.24.6-aliyun.1
cn-shanghai.172.16.1.107   Ready    <none>          18m   v1.24.6-aliyun.1
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_命令行工具_13

查看节点的详细信息。针对具体节点的名称,执行命令kubectl describe nodes <node_name>,可以查看某个节点的详细信息。结果如下:

[root@LYX ~]# kubectl describe nodes cn-shanghai.172.16.1.104
Name:               cn-shanghai.172.16.1.104
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/instance-type=ecs.sn1.medium
                    beta.kubernetes.io/os=linux
                    failure-domain.beta.kubernetes.io/region=us-west-1
                    failure-domain.beta.kubernetes.io/zone=us-west-1a
                    kubernetes.io/hostname=us-west-1.i-rj95bdyyg7sg2dg4o075
                    node-role.kubernetes.io/master=
Annotations:        flannel.alpha.coreos.com/backend-data=null
                    flannel.alpha.coreos.com/backend-type=
                    flannel.alpha.coreos.com/kube-subnet-manager=true
                    flannel.alpha.coreos.com/public-ip=192.168.0.153
                    kubeadm.alpha.kubernetes.io/cri-socket=/var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl=0
CreationTimestamp:  Tue, 26 Feb 2019 09:13:13 +0800
Taints:             node-role.kubernetes.io/master:NoSchedule
Unschedulable:      false 
……

查看应用部署的信息。执行命令kubectl get deployment,即可查看当前命名空间(default)下部署的应用。结果如下:

[root@LYX ~]# kubectl get deployment

NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   2/2     2            2           7m26s
[root@LYX ~]#

查看所有命名空间下的应用。执行命令kubectl get deployment --all-namespaces,结果如下:

[root@LYX ~]# kubectl get deployment --all-namespaces

NAMESPACE     NAME                          READY   UP-TO-DATE   AVAILABLE   AGE
default       nginx-deployment              2/2     2            2           8m28s
kube-system   alicloud-monitor-controller   1/1     1            1           25m
kube-system   coredns                       1/2     2            1           25m
kube-system   csi-provisioner               2/2     2            2           25m
kube-system   metrics-server                1/1     1            1           25m
kube-system   nginx-ingress-controller      2/2     2            2           25m
kube-system   storage-auto-expander         1/1     1            1           21m
kube-system   storage-cnfs                  1/1     1            1           21m
kube-system   storage-monitor               1/1     1            1           21m
kube-system   storage-operator              1/1     1            1           25m
kube-system   storage-snapshot-manager      1/1     1            1           21m
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_vim_14

参数说明:通过指定参数 --all-namespaces,可以显示所有命名空间下的资源对象deployment,其他资源对象也是类似。

查看Pod列表。执行命令kubectl get pods,查看默认命名空间(default)下的pods列表,结果如下:

[root@LYX ~]# kubectl get pods

NAME                                READY   STATUS    RESTARTS   AGE
nginx-controller-cccbz              1/1     Running   0          7m
nginx-deployment-545c55ff9c-dj64b   1/1     Running   0          9m6s
nginx-deployment-545c55ff9c-qbwbc   1/1     Running   0          9m6s
[root@LYX ~]#

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_vim_15

查看Pod的详细信息。针对具体的Pod的名称,执行命令kubectl describe pods <Pod_name>,结果如下:

[root@LYX ~]# kubectl describe pods nginx-deployment-545c55ff9c-dj64b
Name:         nginx-deployment-545c55ff9c-dj64b
Namespace:    default
Priority:     0
Node:         cn-shanghai.172.16.1.107/172.16.1.107
Start Time:   Sat, 22 Apr 2023 21:36:06 +0800
Labels:       app=nginx
              pod-template-hash=545c55ff9c
Annotations:  kubernetes.io/psp: ack.privileged
Status:       Running
IP:           10.1.1.17
IPs:
  IP:           10.1.1.17
Controlled By:  ReplicaSet/nginx-deployment-545c55ff9c

阿里云1+X云计算开发与运维实战——使用kubectl命令行工具对容器进行操作_vim_16

查看service和RC的信息。执行命令kubectl get services,查看service的列表;执行命令kubectl get replicasets,查看部署应用的副本设置列表;执行命令kubectl get rc,查看副本控制器的列表。结果如下:

[root@LYX ~]# kubectl get services
 
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP   34m
[root@LYX ~]#
 
[root@LYX ~]# kubectl get replicasets
 
NAME                          DESIRED   CURRENT   READY   AGE
nginx-deployment-545c55ff9c   2         2         2       11m
[root@LYX ~]#
 
[root@LYX ~]# kubectl get rc
 
NAME               DESIRED   CURRENT   READY   AGE
nginx-controller   1         1         1       9m47s
[root@LYX ~]#

2.4 使用kubectl更新资源对象

1. 对部署的应用进行滚动升级

使用kubectl set image命令,对资源对象Deployment进行滚动升级。例如,本实验中Deployment使用的Nginx镜像版本为1.7,现在将其升级到1.10,执行命令:kubectl set image deployments/<deployment_name> nginx=nginx:1.10,结果如下:

 [root@LYX ~]# kubectl set image deployments/nginx-deployment nginx=nginx:1.10deployment.apps/nginx-deployment image updated

结果说明:本例中,系统先使用新版本的镜像创建一个Pod;创建成功后,将旧版本镜像的Pod再自动缩减1个(此处即为0)。

验证升级结果。执行命令kubectl get pods,找到滚动升级后的Pod。结果如下:

[root@LYX ~]# kubectl get podsNAME
[root@LYX ~]# kubectl get pods nginx-controller-cccbz

NAME                     READY   STATUS    RESTARTS   AGE
nginx-controller-cccbz   1/1     Running   0          23m

查看滚动升级后的Pod的详细信息,确定镜像版本已经更新。执行命令kubectl describe pods <Pod_name>,结果如下:

[root@LYX ~]# kubectl describe pods nginx-deployment-545c55ff9c-dj64b
Name:         nginx-deployment-545c55ff9c-dj64b
Namespace:    default
Priority:     0
Node:         cn-shanghai.172.16.1.107/172.16.1.107
Start Time:   Sat, 22 Apr 2023 21:36:06 +0800
Labels:       app=nginx
              pod-template-hash=545c55ff9c
Annotations:  kubernetes.io/psp: ack.privileged
Status:       Running
IP:           10.1.1.17
IPs:
  IP:           10.1.1.17
Controlled By:  ReplicaSet/nginx-deployment-545c55ff9c
Containers:
  nginx:
    Container ID:   containerd://249ce64808b3b0c70d90d0ce25554da789d11a4cbcef8482e2b2db92c80667a3
    Image:          nginx:1.7
    Image ID:       sha256:c3c8bf3dbe8ba9cabbd8b9c100e36595ced323a682a7050c81e7c66a7e9d27a9
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sat, 22 Apr 2023 21:36:21 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-pbgzb (ro)
Conditions:

2. 对部属的应用进行伸缩

将刚才部署的资源对象Replication Controller伸缩至2副本。执行命令kubectl scale --replicas=2 rc/<RC_name>,结果如下:

[root@LYX ~]# kubectl get rc
 
NAME               DESIRED   CURRENT   READY   AGE
nginx-controller   1         1         1       25m
[root@LYX ~]#
 
[root@LYX ~]# kubectl scale --replicas=2 rc/nginx-controller
 
replicationcontroller/nginx-controller scaled
[root@LYX ~]#

验证伸缩结果。执行命令kubectl get rc,查看伸缩后副本控制器RC的状态,如下所示:

[root@LYX ~]# kubectl get rc
NAME               DESIRED   CURRENT   READY   AGE
nginx-controller   2         2         2       26m
[root@LYX ~]#

执行命令kubectl get pods,查看伸缩后Pod的列表,可以看到nginx-controller存在两个Pod。结果如下:

[root@LYX ~]# kubectl get pods

NAME                                READY   STATUS    RESTARTS   AGE
nginx-controller-54c44              1/1     Running   0          78s
nginx-controller-cccbz              1/1     Running   0          27m
nginx-deployment-545c55ff9c-dj64b   1/1     Running   0          29m
nginx-deployment-545c55ff9c-qbwbc   1/1     Running   0          29m
[root@LYX ~]#

2.5 使用kubectl和运行中的Pod进行交互

在Pod的容器中执行命令。例如在刚才创建的Pod nginx-controller中,打印当前时间。执行命令kubectl exec <Pod_name> date,结果如下:

[root@LYX ~]# kubectl exec nginx-controller-cccbz  date

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Sat Apr 22 14:06:18 UTC 2023
[root@LYX ~]#

进入Pod的容器的虚拟控制台。执行命令kubectl exec -ti <Pod_name> /bin/bash,结果如下:

[root@LYX ~]# kubectl exec -ti nginx-controller-cccbz  /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@nginx-controller-cccbz:/#
root@nginx-controller-cccbz:/# date
Sat Apr 22 14:07:16 UTC 2023
root@nginx-controller-cccbz:/#

查看Pod的日志。使用快捷键Ctrl+P+Q离开容器,返回master节点的命令行界面。执行命令kubectl logs <Pod_name>,即可查看指定日志

[root@LYX ~]# kubectl logs nginx-controller-cccbz

结果说明:此处的Nginx应用如果没有被访问,可能日志为空。

2.6 使用kubectl删除资源对象

删除创建的部署应用nginx-deployment。执行命令kubectl delete deployment <Deployment_name>,结果如下所示:

[root@LYX ~]# kubectl delete deployment nginx-deployment
deployment.apps "nginx-deployment" deleted
[root@LYX ~]#

删除创建的副本控制器nginx-controller。执行命令kubectl delete rc <rc_name>,结果如下所示:

[root@LYX ~]# kubectl delete rc nginx-controller
replicationcontroller "nginx-controller" deleted
[root@LYX ~]#

验证删除结果。执行命令分别查看应用部署,副本控制器,容器组的信息,结果如下所示:

[root@LYX ~]# kubectl get deployment
No resources found in default namespace.
[root@LYX ~]#
[root@LYX ~]# kubectl get rc
No resources found in default namespace.
[root@LYX ~]#
[root@LYX ~]# kubectl get pods
No resources found in default namespace.
[root@LYX ~]#