栏目头部广告

K8S kubectl高频命令详解

一、kubectl工具介绍

kubectl是Kubernetes集群的命令行工具,通过kubectl能够对集群本身进行管理,对资源的对象进行操作,这些操作包括对资源对象的创建、删除和查看等,并能够在集群上进行容器化应用的安装部署。

中文官网解读:https://www.kubernetes.org.cn/4060.html

二、kubectl常用命令介绍

2.1 Pod、Node与宿主之前网络通信方式

K8S kubectl高频命令详解(图1)

2.2 定义测试pod

方案一:直接定义pod,将容器端口映射到宿主

(1)定义pod

[root@ansible K8S]# vim mysql.yaml
apiVersion: v1
kind: Pod
metadata:
  name: mysql-pod
  namespace: stargao
  labels:
    name: mysql-pod
spec:
  containers:
  - name: mysql55
    image: uhub.service.ucloud.cn/library/mysql:5.7.9
    env:
    - name: MYSQL_ROOT_PASSWORD 
      value: redhat
    - name: MYSQL_USER
      value: stargao
    - name: MYSQL_PASSWORD
      value: redhat
    ports:
    - containerPort: 3306
      hostPort: 33306 # 映射宿主端口

(2)创建K8S单pod

# 创建pod
[root@ansible K8S]# kubectl apply -f mysql.yaml
pod/mysql-pod created

# 查看pod创建情况
[root@ansible K8S]# kubectl get pod
NAME        READY   STATUS              RESTARTS   AGE
mysql-pod   0/1     ContainerCreating   0          21s

[root@ansible K8S]# kubectl get pod
NAME        READY   STATUS    RESTARTS   AGE
mysql-pod   1/1     Running   0          22s

方案二:定义RC与SVC

(1)定义ReplicationController副本控制器,简称RC

[root@ansible K8S]# vim mysql-rc.yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: mysql-rc
  labels:
    name: mysql-rc
spec:
  replicas: 3
  selector:
    name: stargao-mysql-template
  template:
    metadata:
      labels:
        name: stargao-mysql-template
    spec:
      containers:
      - name: stargao-mysql-containers
        image: uhub.service.ucloud.cn/library/mysql:5.7.9
        env:
        - name: MYSQL_ROOT_PASSWORD 
          value: redhat
        - name: MYSQL_USER
          value: stargao
        - name: MYSQL_PASSWORD
          value: redhat
        ports:
        - containerPort: 3306

(2)定义关联 service,简称SVC

[root@ansible K8S]# vim mysql-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: mysql-svc
  labels:
    name: mysql-svc
spec:
  type: NodePort
  ports:
  - port: 3306        # pod暴露到集群IP上的端口
    targetPort: 3306  # 容器端口
    protocol: TCP
    nodePort: 33306   # 集群IP,映射到node节点(宿主)端口 
  selector:
    name: stargao-mysql-template

(3)查看service情况

[root@ansible k8s]# kubectl describe services
Name:                     mysql-svc
Namespace:                stargao
Labels:                   name=mysql-svc
Annotations:              kubectl.kubernetes.io/last-applied-configuration:
                            {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"name":"mysql-svc"},"name":"mysql-svc","namespace":"stargao"},"...
Selector:                 name=stargao-mysql-template
Type:                     NodePort
IP:                       10.2.184.156
Port:                     <unset>  3306/TCP
TargetPort:               3306/TCP
NodePort:                 <unset>  33306/TCP
Endpoints:                192.168.0.149:3306,192.168.0.194:3306,192.168.0.212:3306
Session Affinity:         None
External Traffic Policy:  Cluster

(4)创建多副本Pod

# 创建pod
[root@ansible K8S]# kubectl apply -f mysql-rc.yaml 
replicationcontroller/mysql-rc created

# 创建SVC
[root@ansible K8S]# kubectl apply -f mysql-svc.yaml 
service/mysql-svc created

# 查看pod创建情况
[root@ansible K8S]# kubectl get pod
NAME             READY   STATUS    RESTARTS   AGE
mysql-pod        1/1     Running   0          13h
mysql-rc-d4glt   1/1     Running   0          10s
mysql-rc-w2kc4   1/1     Running   0          10s
mysql-rc-w78jw   1/1     Running   0          10s

2.3 常用命令演示

(1)pod相关操作

# 创建pod
[root@ansible K8S]# kubectl apply -f mysql.yaml

# pod日志信息查询
[root@ansible ~]# kubectl logs mysql-pod 
Initializing database
2021-08-18T15:55:52.474548Z 0 [Warning] InnoDB: New log files created, LSN=45790
2021-08-18T15:55:52.684072Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2021-08-18T15:55:52.763803Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: c3fa3f9b-003c-11ec-b1f2-d20a0443d042.
2021-08-18T15:55:52.765482Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2021-08-18T15:55:52.766196Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2021-08-18T15:55:53.465696Z 1 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2021-08-18T15:55:53.465755Z 1 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2021-08-18T15:55:53.465774Z 1 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2021-08-18T15:55:53.465788Z 1 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2021-08-18T15:55:53.465822Z 1 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.

# 查看pod节点运行情况
[root@ansible ~]# kubectl get pod
NAME             READY   STATUS    RESTARTS   AGE
mysql-pod        1/1     Running   0          14h
mysql-rc-d4glt   1/1     Running   0          83m
mysql-rc-w2kc4   1/1     Running   0          83m
mysql-rc-w78jw   1/1     Running   0          83m

[root@ansible K8S]# kubectl get pods -o=wide
NAME             READY   STATUS    RESTARTS   AGE    IP              NODE            NOMINATED NODE   READINESS GATES
mysql-rc-d4glt   1/1     Running   0          152m   192.168.0.149   192.168.0.107   <none>           <none>
mysql-rc-w2kc4   1/1     Running   0          152m   192.168.0.194   192.168.0.107   <none>           <none>
mysql-rc-w78jw   1/1     Running   0          152m   192.168.0.212   192.168.0.107   <none>           <none>
# 查看pod节点详情
[root@ansible ~]# kubectl describe pods
Name:               mysql-pod
Namespace:          stargao
Priority:           0
PriorityClassName:  <none>
Node:               192.168.0.107/192.168.0.107
Start Time:         Wed, 18 Aug 2021 23:55:30 +0800
Labels:             name=mysql-pod
Annotations:        kubectl.kubernetes.io/last-applied-configuration:
                      {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"name":"mysql-pod"},"name":"mysql-pod","namespace":"stargao"},"spec...
Status:             Running
IP:                 192.168.0.3
Containers:
  mysql55:
    Container ID:   containerd://92b8178575d1397b95c4d071b83ce0147c70f8bbdf449b13b972fc217a7ff23e
    Image:          uhub.service.ucloud.cn/library/mysql:5.7.9
    Image ID:       uhub.service.ucloud.cn/library/mysql@sha256:cafa4a980ebb935e26f9896895ba6a6e9466c7c33cd172bce1050883300ae30e
    Port:           3306/TCP
    Host Port:      33306/TCP
    State:          Running
      Started:      Wed, 18 Aug 2021 23:55:50 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      MYSQL_ROOT_PASSWORD:  redhat
      MYSQL_USER:           stargao
      MYSQL_PASSWORD:       redhat
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-8h5jt (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-8h5jt:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-8h5jt
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300

# 删除pod
[root@ansible K8S]# kubectl delete -f  mysql.yaml
pod "mysql-pod" deleted

# 动态查看Pod日志输出
[root@ansible K8S]# kubectl logs -f mysql-pod  -c mysql55

语法:kubectl logs –f <pod-name> -c <container-name>

# 查看SVC运行情况
[root@ansible K8S]# kubectl get svc
NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
mysql-svc   NodePort   10.2.184.156   <none>        3306:33306/TCP   11s

[root@ansible K8S]# kubectl get svc -o=wide -n stargao           
NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE   SELECTOR
mysql-svc   NodePort   10.2.184.156   <none>        3306:33306/TCP   82m   name=stargao-mysql-template

[root@192-168-0-107 ~]# netstat -antulp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      8794/sshd           
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1275/master         
tcp        0      0 0.0.0.0:33306           0.0.0.0:*               LISTEN      9147/kube-proxy

【注】-n指定命名空间;-o=wide输出带有附加信息的纯文本格式。对于Pod对象,将会包含Node名称。

(2)node相关操作

# 查看node运行情况
[root@ansible ~]# kubectl get nodes
NAME            STATUS                     ROLES    AGE   VERSION
192.168.0.107   Ready                      <none>   28d   v1.20.6
192.168.0.220   Ready                      <none>   28d   v1.20.6
192.168.0.48    Ready,SchedulingDisabled   master   28d   v1.20.6
192.168.0.88    Ready,SchedulingDisabled   master   28d   v1.20.6
192.168.0.94    Ready,SchedulingDisabled   master   28d   v1.20.6

[root@ansible K8S]# kubectl get nodes -o=wide
NAME            STATUS                     ROLES    AGE   VERSION   INTERNAL-IP     EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION               CONTAINER-RUNTIME
192.168.0.107   Ready                      <none>   28d   v1.20.6   192.168.0.107   <none>        CentOS Linux 7 (Core)   4.19.0-9.el7.ucloud.x86_64   containerd://1.4.3
192.168.0.220   Ready                      <none>   28d   v1.20.6   192.168.0.220   <none>        CentOS Linux 7 (Core)   4.19.0-9.el7.ucloud.x86_64   containerd://1.4.3
192.168.0.48    Ready,SchedulingDisabled   master   28d   v1.20.6   192.168.0.48    <none>        CentOS Linux 7 (Core)   4.19.0-9.el7.ucloud.x86_64   containerd://1.4.3
192.168.0.88    Ready,SchedulingDisabled   master   28d   v1.20.6   192.168.0.88    <none>        CentOS Linux 7 (Core)   4.19.0-9.el7.ucloud.x86_64   containerd://1.4.3
192.168.0.94    Ready,SchedulingDisabled   master   28d   v1.20.6   192.168.0.94    <none>        CentOS Linux 7 (Core)   4.19.0-9.el7.ucloud.x86_64   containerd://1.4.3

# 查看node节点详情
[root@ansible ~]# kubectl describe nodes
Name:               192.168.0.107
Roles:              <none>
Labels:             UhostID=uhost-pxzclck2
                    beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=192.168.0.107
                    kubernetes.io/os=linux
                    node.uk8s.ucloud.cn/instance_type=uhost
                    node.uk8s.ucloud.cn/machine_type=N
                    node.uk8s.ucloud.cn/resource_id=uhost-pxzclck2
                    role.node.kubernetes.io/k8s-node=true
                    topology.kubernetes.io/region=cn-sh2
                    topology.kubernetes.io/zone=cn-sh2-02
                    topology.udisk.csi.ucloud.cn/region=cn-sh2
                    topology.udisk.csi.ucloud.cn/zone=cn-sh2-02
Annotations:        csi.volume.kubernetes.io/nodeid: {"udisk.csi.ucloud.cn":"192.168.0.107"}
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Thu, 22 Jul 2021 10:57:11 +0800
Taints:             <none>
Unschedulable:      false
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  MemoryPressure   False   Thu, 19 Aug 2021 15:02:38 +0800   Thu, 22 Jul 2021 10:57:11 +0800   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Thu, 19 Aug 2021 15:02:38 +0800   Thu, 22 Jul 2021 10:57:11 +0800   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure      False   Thu, 19 Aug 2021 15:02:38 +0800   Thu, 22 Jul 2021 10:57:11 +0800   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready            True    Thu, 19 Aug 2021 15:02:38 +0800   Thu, 22 Jul 2021 10:57:21 +0800   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  192.168.0.107
  Hostname:    192.168.0.107
Capacity:
 cpu:                2
 ephemeral-storage:  20470Mi
 hugepages-2Mi:      0
 memory:             3873420Ki
 pods:               110
Allocatable:
 cpu:                1800m
 ephemeral-storage:  19317915617
 hugepages-2Mi:      0
 memory:             2719486974
 pods:               110
System Info:
 Machine ID:                 2b2b101ebec37b13cb767b69ceb77af5
 System UUID:                aaf40fab-d194-4867-82f3-77386b76b8a5
 Boot ID:                    8a776612-6a3f-4e75-97c9-2f7c7364ab0a
 Kernel Version:             4.19.0-9.el7.ucloud.x86_64
 OS Image:                   CentOS Linux 7 (Core)
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  containerd://1.4.3
 Kubelet Version:            v1.20.6
 Kube-Proxy Version:         v1.20.6
ProviderID:                  UCloud://cn-sh2-02//uk8s-2lynocjx-n-39ffh
Non-terminated Pods:         (6 in total)
  Namespace                  Name                        CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                  ----                        ------------  ----------  ---------------  -------------  ---
  kube-system                coredns-6667d7f4c6-6mjwb    100m (5%)     0 (0%)      70Mi (2%)        170Mi (6%)     28d
  kube-system                csi-udisk-mzx4k             0 (0%)        0 (0%)      0 (0%)           0 (0%)         28d
  stargao                    mysql-pod                   0 (0%)        0 (0%)      0 (0%)           0 (0%)         15h
  stargao                    mysql-rc-d4glt              0 (0%)        0 (0%)      0 (0%)           0 (0%)         105m
  stargao                    mysql-rc-w2kc4              0 (0%)        0 (0%)      0 (0%)           0 (0%)         105m
  stargao                    mysql-rc-w78jw              0 (0%)        0 (0%)      0 (0%)           0 (0%)         105m
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests   Limits
  --------           --------   ------
  cpu                100m (5%)  0 (0%)
  memory             70Mi (2%)  170Mi (6%)
  ephemeral-storage  0 (0%)     0 (0%)

三、K8S核心组件健康状态

3.1 K8S集群信息查看

# 查看集群信息
[root@ansible K8S]# kubectl cluster-info 
Kubernetes master is running at https://192.168.0.99:6443
CoreDNS is running at https://192.168.0.99:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
# 查看etcd组件的健康状况
[root@ansible K8S]# kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
controller-manager   Healthy   ok                  
scheduler            Healthy   ok                  
etcd-0               Healthy   {"health":"true"}   
etcd-2               Healthy   {"health":"true"}   
etcd-1               Healthy   {"health":"true"}

【注】etcd 保存了整个集群的状态

3.2 K8S核心组件服务运行情况查看

kube-apiserver                   # 资源对象的唯一操作入口
kube-controller-manager   # 集群故障检测和恢复的自动化工作
kube-scheduler                  # 进行资源调度
etcd                                    # 保存了整个集群的状态
kube-proxy                        # 写iptables规则
kubelet                               # 容器的生命周期管理
docker                                # 容器运行时环境

(1)查看组件运行情况

systemctl status kube-apiserver
systemctl status kube-controller-manager
systemctl status kube-scheduler
systemctl status kube-proxy
systemctl status etcd
systemctI status docker

(2)查看组件日志信息

journalctl -u kube-apiserver
journalctl -u kube-controller-manager
journalctl -u kube-scheduler
journalctl -u kube-proxy
journalctl -u etcd
journalctl -u docker

作者:UStarGao
链接:https://www.starcto.com/k8s/211.html
来源:STARCTO
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处

UCloud云平台推荐


UCloud新用户专属注册连接

UCloud CDN超值特惠专场

UCloud全球云主机(UHost/VPS)大促页面

UCloud快杰云主机大促页面

加载中~
文章详情页广告

随便看看

底部广告
`