以下内容均来自个人笔记并重新梳理,如有错误欢迎指正!
如果对您有帮助,烦请点赞、关注、转发!如果您有其他想要了解的,欢迎私信联系我~
写在前边
笔者在之前的文章中已经陆续介绍过 Kubernetes 的部分命令,本文将专题介绍 Kubernetes 的常用命令,处理日常工作基本够用了。
集群相关
1、查看集群信息
kubectl cluster-info
# 输出信息
Kubernetes master is running at https://172.17.xx.xx:6443
CoreDNS is running at https://172.17.xx.xx:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
Metrics-server is running at https://172.17.xx.xx:6443/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
2、查看集群服务
kubectl get apiservice
🔔 全部为 True 则正常
# 输出信息
NAME SERVICE AVAILABLE AGE
v1. Local True 76d
v1.admissionregistration.k8s.io Local True 76d
v1.apiextensions.k8s.io Local True 76d
v1.apps Local True 76d
v1.authentication.k8s.io Local True 76d
v1.authorization.k8s.io Local True 76d
v1.autoscaling Local True 76d
v1.batch Local True 76d
v1.certificates.k8s.io Local True 76d
v1.coordination.k8s.io Local True 76d
v1.events.k8s.io Local True 76d
v1.helm.cattle.io Local True 10d
v1.k3s.cattle.io Local True 10d
v1.networking.k8s.io Local True 76d
v1.rbac.authorization.k8s.io Local True 76d
v1.scheduling.k8s.io Local True 76d
v1.storage.k8s.io Local True 76d
v1beta1.admissionregistration.k8s.io Local True 76d
v1beta1.apiextensions.k8s.io Local True 76d
v1beta1.authentication.k8s.io Local True 76d
v1beta1.authorization.k8s.io Local True 76d
v1beta1.batch Local True 76d
v1beta1.certificates.k8s.io Local True 76d
v1beta1.coordination.k8s.io Local True 76d
v1beta1.discovery.k8s.io Local True 76d
v1beta1.events.k8s.io Local True 76d
v1beta1.extensions Local True 76d
v1beta1.metrics.k8s.io kube-system/metrics-server True 76d
v1beta1.networking.k8s.io Local True 76d
v1beta1.node.k8s.io Local True 76d
v1beta1.policy Local True 76d
v1beta1.rbac.authorization.k8s.io Local True 76d
v1beta1.scheduling.k8s.io Local True 76d
v1beta1.storage.k8s.io Local True 76d
v2beta1.autoscaling Local True 76d
v2beta2.autoscaling Local True 76d
3、查看集群组件
kubectl get componentstatus
# 输出信息
NAME STATUS MESSAGE ERROR
scheduler Healthy ok
controller-manager Healthy ok
etcd-0 Healthy {"health":"true"}
4、查看集群版本
kubectl version
--short 选项:精简输出信息
--client 选项:之查看客户端版本
# 输出信息
Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.12", GitCommit:"2cb4598553d0a2ca5f3eb7980c99cd8236cc5011", GitTreeState:"clean", BuildDate:"2021-06-16T13:00:29Z", GoVersion:"go1.15.13", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.16+k3s-", GitCommit:"", GitTreeState:"clean", BuildDate:"2022-09-17T15:17:58Z", GoVersion:"go1.15.14", Compiler:"gc", Platform:"linux/amd64"}
5、查看集群 API 版本
kubectl api-versions
# 输出信息
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
helm.cattle.io/v1
k3s.cattle.io/v1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
节点相关
1、查看节点状态
kubectl get node
# 输出信息
master01 Ready etcd,master 76d v1.19.16+k3s-
2、查看节点资源使用情况
kubectl top node
# 输出信息
NAME CPU(cores) CPU% MEMORY(bytes) MEMORY%
master01 3283m 41% 36941Mi 58%
3、查看节点详细信息
kubectl describe node <node-name>
# 输出信息
Name: master01
Roles: etcd,master
Labels: kubernetes.io/arch=amd64
kubernetes.io/hostname=master01
kubernetes.io/os=linux
node-role.kubernetes.io/etcd=true
node-role.kubernetes.io/master=true
Annotations: xxxx
CreationTimestamp: Tue, 21 May 2024 11:36:35 +0800
Taints: <none>
Unschedulable: false
Lease:
HolderIdentity: master01
AcquireTime: <unset>
RenewTime: Mon, 05 Aug 2024 14:21:42 +0800
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
NetworkUnavailable False Thu, 25 Jul 2024 16:56:35 +0800 Thu, 25 Jul 2024 16:56:35 +0800 FlannelIsUp Flannel is running on this node
MemoryPressure False Mon, 05 Aug 2024 14:18:53 +0800 Tue, 21 May 2024 11:36:35 +0800 KubeletHasSufficientMemory kubelet has sufficient memory available
DiskPressure False Mon, 05 Aug 2024 14:18:53 +0800 Thu, 30 May 2024 17:43:57 +0800 KubeletHasNoDiskPressure kubelet has no disk pressure
PIDPressure False Mon, 05 Aug 2024 14:18:53 +0800 Tue, 21 May 2024 11:36:35 +0800 KubeletHasSufficientPID kubelet has sufficient PID available
Ready True Mon, 05 Aug 2024 14:18:53 +0800 Thu, 30 May 2024 17:43:57 +0800 KubeletReady kubelet is posting ready status
Addresses:
InternalIP: 172.17.xx.xx
Hostname: master01
Capacity:
cpu: 8
ephemeral-storage: 51474024Ki
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 64757920Ki
pods: 235
Allocatable:
cpu: 8
ephemeral-storage: 52709400575
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 64655520Ki
pods: 235
System Info:
Machine ID: xxxx
System UUID: xxxx
Boot ID: 0bf721f7-c072-4a24-9f7d-fc9f51007f65
Kernel Version: 3.10.0-1127.19.1.el7.x86_64
OS Image: CentOS Linux 7 (Core)
Operating System: linux
Architecture: amd64
Container Runtime Version: containerd://1.4.11-k3s1
Kubelet Version: v1.19.16+k3s-
Kube-Proxy Version: v1.19.16+k3s-
PodCIDR: 10.42.0.0/24
PodCIDRs: 10.42.0.0/24
Non-terminated Pods: (110 in total)
Namespace Name CPU Requests CPU Limits Memory Requests Memory Limits AGE
--------- ---- ------------ ---------- --------------- ------------- ---
kube-system coredns-5d69dc75db-ddhb2 100m (1%) 0 (0%) 70Mi (0%) 170Mi (0%) 10d
kube-system coredns-5d69dc75db-m5dcj 100m (1%) 0 (0%) 70Mi (0%) 170Mi (0%) 10d
kube-system dns-autoscaler-5b66f57c-lccr9 200m (2%) 0 (0%) 150Mi (0%) 0 (0%) 10d
kube-system fluentd-jj5hk 100m (1%) 1 (12%) 100Mi (0%) 3Gi (4%) 10d
kube-system kube-state-metrics-84c8c679b-9fxdp 0 (0%) 0 (0%) 0 (0%) 0 (0%) 10d
kube-system metrics-server-7b4f8b595-gtbx9 0 (0%) 0 (0%) 0 (0%) 0 (0%) 10d
kube-system nfs-client-provisioner-lanhuapp-d549cc59f-7l4r6 0 (0%) 0 (0%) 0 (0%) 0 (0%) 10d
kube-system nginx-ingress-controller-77ff74d4fc-8dlnk 0 (0%) 0 (0%) 0 (0%) 0 (0%) 10d
kube-system svclb-ingress-nginx-ssf2h 0 (0%) 0 (0%) 0 (0%) 0 (0%) 10d
kube-system svclb-kube-state-metrics-bcdbm 0 (0%) 0 (0%) 0 (0%) 0 (0%) 10d
Allocated resources:
(Total limits may be over 100 percent, i.e., overcommitted.)
Resource Requests Limits
-------- -------- ------
cpu 3470m (43%) 79700m (996%)
memory 15718Mi (24%) 167972Mi (266%)
ephemeral-storage 0 (0%) 0 (0%)
hugepages-1Gi 0 (0%) 0 (0%)
hugepages-2Mi 0 (0%) 0 (0%)
Events: <none>
4、节点标签命令
# 新增节点标签
kubectl label node <node-name> key=value
# 删除节点标签
kubectl label node <node-name> key-
# 修改节点标签
kubectl label node <node-name> key=value --overwrite
# 查看节点标签
kubectl get node <node-name> --show-labels111
5、节点污点命令
# 新增污点标记
kubectl taint node <node-name> key=value:NoSchedule
kubectl taint node <node-name> key=value:NoExecute
# 删除污点标记:
kubectl taint nodes <node-name> key-
命名空间相关
1、创建命名空间
kubectl create namespace <namespace>
2、查看命名空间
kubectl get namespace
# 输出信息
NAME STATUS AGE
default Active 76d
kube-system Active 76d
3、删除命名空间
kubectl delete namespace <namespace>
4、切换命名空间
kubectl config set-context --current --namespace <namespace>
控制器相关
以 Deployment 为例
1、创建控制器
kubectl create deployment <deployment-name> --image=<image-name> --replicas=<num>
🔔 --image 选项:指定镜像
🔔 --replicas 选项:指定副本数
🔔 --env 选项:指定 ENV 环境变量
2、查看控制器
# 查看全部控制器列表
kubectl get deployment
# 查看控制器详细信息
kubectl describe deployment <deployment-name>
# 查看控制器资源清单
kubectl get deployment <deployment-name> -oyaml
3、更新控制器
# 更新镜像
kubectl set image deployment <deployment-name> <container-name>=<image-name>
# 新增或修改 ENV 环境变量
kubectl set env deployment <deployment-name> key=value
# 删除 ENV 环境变量
kubectl set env deployment <deployment-name> key-
# 新增或修改资源限制
kubectl set resources deployment <deployment-name> --requests=cpu=100m,memory=256Mi --limits=cpu=100m,memory=256Mi
# 删除资源限制
kubectl set resources deployment <deployment-name> --requests=cpu=0,memory=0 --limits=cpu=0,memory=0
===================================================================================
# 通过 patch 更新
## 新增 command 参数
kubectl patch deployment <deployment-name> --type json -p \
'[{"op":"add", "path":"/spec/template/spec/containers/0/command", "value":["sh","-c","sleep 3000"]}]'
## 删除 command 参数
kubectl patch deployment <deployment-name> --type json -p \
'[{"op":"remove", "path":"/spec/template/spec/containers/0/command"}]'
## 替换 command 参数
kubectl patch deployment <deployment-name> --type json -p \
'[{"op":"replace", "path":"/spec/template/spec/containers/0/command", "value":["sh","-c","sleep 3600"]}]'
🔔 kubectl patch 可以使用 --dry-run 进行格式检查,追加 -oyaml 查看资源清单
===================================================================================
# 通过 edit 更新(类似 vi 文本操作)
kubectl edit deployment <deployment-name>
4、删除控制器
# 删除全部控制器
kubectl delete deployment --all
# 删除指定名称控制器
kubectl delete deployment <deployment-name>
5、副本伸缩
kubectl scale deployment <deployment-name> --replicas=<num>
6、滚动重启
# 重启全部控制器
kubectl rollout restart deployment
# 重启指定名称控制器
kubectl rollout restart deployment <deployment-name>
Pod 相关
1、创建临时 Pod
kubectl run --rm -it --image=busybox sh
2、查看 Pod
# 查看全部 Pod 列表
kubectl get pod
# 查看 Pod 详细信息
kubectl describe pod <pod-name>
# 查看 Pod 资源清单
kubectl get pod <pod-name> -oyaml
# 查看 Pod 日志
## 方式一:通过 Pod 名称查看
kubectl logs -f <pod-name>
## 方式二:通过 Pod 标签查看
kubectl logs -f -l key=value
🔔 -c 选项:指定 Pod 内 Container 的名称,当 Pod 内有多个业务容器时需要指定
🔔 -f 选项:查看实时日志
🔔 -n 选项:指定命名空间
🔔 -A 选项:所有命名空间
🔔 -o 选项:指定输出格式,有 wide、yaml、json、name、custom-columns 等
🔔 -v 选项:指定输出详细内容,6 表示输出 http 请求,8 表示输出 http 请求体、响应头、响应体内容
3、删除 Pod
kubectl delete po <pod-name>
🔔 若执行后 Pod 长时间处于 Terminating 状态,添加参数 --force --grace-period 0 即可强制删除,但要谨慎使用!
4、进入 Pod 容器
# 方式一:通过 Pod 名称进入
kubectl exec -it <pod-name> bash
# 方式二:通过 Deployment 名称进入
kubectl exec -it deployment/<deployment-name> bash
🔔 -c 选项:指定 Pod 内 Container 的名称,当 Pod 内有多个业务容器时需要指定
# 不进入容器直接执行命令
kubectl exec -it <pod-name> bash -c "<command>"
或
kubectl exec <pod-name> -- sh -c "<command>"
Service 相关
1、创建 Service
# 方法一:基于已有 Deployment 对象创建
kubectl expose deployment <deployment-name> --type=<Servcie 类型> --port=<port> --targetPort=<targetPort>
# 示例:
kubectl expose deployment demo-deployment --type=ClusterIP --port=80 --targetPort=80
# 方法二:命令行创建
kubectl create servcie <Servcie 类型> <service-name> --tcp=<port>:<targetPort>
# 示例:
kubectl create servcie clusterip demo-servcie --tcp=80:80
2、查看 Service
# 查看全部 Service 列表
kubectl get service
# 查看 Service 详细信息
kubectl describe service <service-name>
# 查看 Service 资源清单
kubectl get service <service-name> -oyaml
3、删除 Service
kubectl delete service <service-name>
资源对象缩写
部分资源对象支持缩写,在执行命令时使用缩写可以提高操作效率
# 查看所有资源对象
kubectl api-resources
# 资源对象缩写(部分)
kubectl get all # 查看所有 Workload(pod、svc、ds、deploy、rs、sts、job、cj)
kubectl get cj # 查看 CronJob
kubectl get cm # 查看 ConfigMap
kubectl get cs # 查看 ComponentStatus
kubectl get deploy # 查看 Deployment
kubectl get ds # 查看 DaemonSet
kubectl get ep # 查看 Endpoint
kubectl get ev # 查看 Event,即当前 Namespace 的事件
kubectl get hpa # 查看 HPA
kubectl get ing # 查看 Ingress
kubectl get lease -A # 查看集群健康状态信息
kubectl get no # 查看 Node
kubectl get ns # 查看 Namespace
kubectl get po # 查看 Pod
kubectl get pv # 查看 PersistentVolume
kubectl get pvc # 查看 PersistentVolumeClaim
kubectl get rs # 查看 ReplicaSet
kubectl get sa # 查看 ServiceAccount
kubectl get sc # 查看 StorageClass
kubectl get sts # 查看 StatefulSet
kubectl get svc # 查看 Service
kubectl 命令设置别名
cat >> /root/.bashrc <<EOF
source <(kubectl completion bash)
# kubectl 别名
alias k="kubectl"
alias kc="kubectl get cm -o wide"
alias kd="kubectl get deploy -o wide"
alias ke="kubectl get ep"
alias ki="kubectl get ing"
alias kn="kubectl get no -o wide"
alias kp="kubectl get po -o wide"
alias wp="watch kubectl get po -o wide"
alias kr="kubectl get rs"
alias ks="kubectl get svc"
alias krrd="kubectl rollout restart deploy"
alias krsd="kubectl rollout status deploy"
alias krrs="kubectl rollout restart sts"
alias krss="kubectl rollout status sts"
complete -F __start_kubectl k
EOF
source /root/.bashrc