kubectl 命令行工具

发布时间: 更新时间: 总字数:2553 阅读时间:6m 作者:IP:上海 网址

k8s 常用命令

kubectl 命令分类

kubectl 的命令分为 3 类:

  • 陈述式命令(Imperative Commands),如 run、expose、delete、get 等
  • 陈述式对象命令(Imperative Object Commands):create -f, delete -f, replace -f
  • 声明式对象命令(Declarative Object Commands):apply -f

基础命令

bash completion

# 在 bash 中设置当前 shell 的自动补全,依赖:apt install bash-completion
source <(kubectl completion bash)

# 在 bash 中设置永久自动补全
echo "source <(kubectl completion bash)" >> ~/.bashrc

version

client 和 server 的版本信息

  • client 端 kubectl 版本信息
  • server 端 k8s 版本信息
kubectl version

config

切换空间

$ kubectl config set-context $(kubectl config current-context) --namespace=<insert-namespace-name-here>
# Validate it
$ kubectl config view | grep namespace:

namespace

kubectl get ns
kubectl get namespaces
kubectl get ns/default
kubectl get ns/default -o [wide|yaml|json]

kubectl create namespace dev
kubectl describe ns/default

kubectl delete namespace dev
kubectl delete ns/dev
kubectl delete ns/dev ns/testing
# cat namespace-dev.yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
  • 切换空间
kubectl config set-context $(kubectl config current-context) --namespace=<insert-namespace-name-here>

components

查看scheduler/controller-manager/etcd等组件 Healthy

kubectl get cs -o wide
kubectl get componentstatus

cluster info

查看kubernetes master(apiserver)组件running

kubectl cluster-info

api-resources

kubectl api-resources

api-versions

kubectl api-versions

get

  • 获取当前命名空间的所有资源
kubectl get all
  • 获取指定类型的跨命名空间的所有资源
kubectl get pod -A
kubectl get ingress -A
kubectl get ingressroute -A

set

更新镜像

kubectl set image deployment/nginx-deployment nginx=nginx:1.9.1

patch

kubectl patch deployment nginx-deployment -p '{"spec":{"replicas":5}}'
kubectl patch deployment nginx-deployment -p '{"spec":{"strategy":{"roolingUpdate": {"maxSurge":1, "maxUnavailable": 0}}}}'

Nodes

get

kubectl get nodes
kubectl get nodes -o wide
kubectl get nodes --show-labels

kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints --no-headers
  • -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints: 这是关键的输出格式选项,用于定义你想要显示的列以及这些列对应的数据来源。
  • -o--output 的简写,表示你希望自定义输出格式。
  • custom-columns= 指定了你想要使用自定义列。
  • NAME:.metadata.name: 这定义了第一列。
  • NAME: 这是你给这一列起的标题。
  • .metadata.name: 这是 Kubernetes 资源路径,表示从每个节点的元数据(metadata)中获取其名称(name)。 --no-headers: 在输出结果中不显示列的标题行

describe

kubectl describe nodes

支持显示节点 Allocated resources 信息,核心是通过获取节点的 Pod 计算而出,参考 describeNode 方法

cordon

cordon 用来为节点配置警戒线:设置完后 node 节点的 STATUS 会加上 SchedulingDisabled 标记,表示此节点处于不可调度的状态。已经在此节点上运行的 Pod 不会被删除

kubectl cordon node1

# 等价于
kubectl taint nodes <你的节点名称> node.kubernetes.io/unschedulable:NoSchedule

$ kubectl get nodes
node1     Ready,SchedulingDisabled   worker   90d   v1.28.2

# 取消 cordon
kubectl uncordon node1
命令 效果 推荐场景
kubectl cordon <node-name> 推荐。添加 unschedulable 污点,阻止新 Pod 调度。 准备进行节点维护,或临时隔离节点,不希望影响现有服务。
kubectl taint ... 手动添加 unschedulable 污点,效果同 cordon 当需要脚本化或精细控制污点时使用,但对于此特定场景,cordon 更佳。
kubectl drain <node-name> 标记为不可调度驱逐现有 Pod。 需要清空节点以进行重启、升级或下线等破坏性操作。

drain

drain 用来为节点配置污点:设置完后该节点不可调度,容器会驱散

kubectl drain node1 --ignore-daemonsets

explain

kube api 文档,帮助开发人员查看yaml配置信息

kubectl explain <type>.<fieldName>[.<fieldName>]

kubectl explain pod
kubectl explain pod.kind
kubectl explain pod.spec
kubectl explain pod.spec.containers.lifecycle
...
  • kubectl explain pod
kubectl explain pod
  • kubectl explain pod.spec.containers.lifecycle
kubectl explain pod lifecycle

Pod, Pod Controller, Service

示例:

  • Deployment -> nginx-dp -> nginx pod
  • Service -> nginx-dp

下面依次创建 Pod、svc,资源如下:

kubectl get all
NAME                                          READY   STATUS    RESTARTS   AGE
pod/nginx-dp-5cc7cc95cb-ll4s4                 1/1     Running   0          71s

NAME                             TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/kubernetes               ClusterIP   10.116.0.1     <none>        443/TCP   2d1h

NAME                                     READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx-dp                 1/1     1            1           72s

NAME                                                DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-dp-5cc7cc95cb                 1         1         1       73s

Pod

查看所有集群 pod 状态

kubectl get pods
kubectl get pods -n kube-public
kubectl get pods -n kube-system
kubectl get pods --all-namespaces
kubectl get pods --all-namespaces -o wide

# 查看 pod 的 uuid,与 /var/lib/kubelet/pods/<uuid> 向对应
kubectl get pods -A -o custom-columns=NodeName:.spec.nodeName,PodName:.metadata.name,PodUID:.metadata.uid

根据标签获取 pod

kubectl get pod -l app,release
kubectl get pod -l app=demo --show-labels
kubectl get pod -l app=nginx --show-labels

kubectl get pod -l "app in (nginx, demo)"

kubectl get pod nginx -o wide

# 非默认namespace,需要指定具体namespace
kubectl -n kube-system get pods -o wide

强制删除 pod

kubectl delete pods <pod> --grace-period=0 --force

kubectl exec

进入容器执行命令:

kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...] [options]
kubectl exec <pod-name> -- pwd
kubectl exec pod/<pod-name> -it -- [/bin/sh|bash]
  • sidecar 容器访问
kubectl exec -n <namespace> -it <pod-name> -c <container-name> -- [/bin/sh|bash]

kubectl logs

查看容器日志:

kubectl logs -f pod/<pod-name>
  • sidecar 容器访问
kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER] [options]
kubect logs --tail=5 -n <namespace> <pod-name> -c <container-name>
  • 之前崩溃容器的日志
kubectl logs --previous (POD | TYPE/NAME) [-c CONTAINER] [options]

kubectl port-forward

解决服务暴露问题

kubectl port-forward <pod-name> 8080:<pod-port>
kubectl port-forward service/<service-name> 8080:<service-port>
kubectl port-forward <ingress-pod-name> 8080:<ingress-port>

示例:

kubectl port-forward svc/kubernetes-dashboard 8443:443 -n kubernetes-dashboard

Deployment

kubectl get deployment
  • 创建资源
kubectl create deployment nginx-dp --image=nginx
kubectl get pod -o wide
# 在master节点访问资源
curl <pod-ip>
# 删除pod
kubectl delete pod/nginx-dp-5cc7cc95cb-ll4s4

SVC

kubectl create service -h
  • 查看所有集群服务状态
kubectl get svc --all-namespaces

创建 clusterip

kubectl create service clusterip nginx-dp --tcp=80:80
  • 查看
kubectl get svc/nginx-dp -o wide
kubectl describe svc/nginx-dp
  • 访问
  1. 通过 clusterip 可以访问到 nginx 的服务
kubectl get svc -n kube-system
  1. 通过域名访问,查看coredns/kube-dns的地址,修改/etc/resolv.confnameserver
  2. 访问域名nginx-dp.default.svc.cluster.local

创建 nodeport

# kubectl create service nodeport nginx-dp --tcp=80:80
service/nginx-dp created
# kubectl get svc
NAME                     TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
nginx-dp                 NodePort    10.116.14.211   <none>        80:32761/TCP   45s

通过 nodeip:32761 访问,该实现通过iptable dnat实现

Label

为指定节点设置 label

kubectl label nodes <node-name> <label-key>=<label-value>
kubectl label nodes 172.20.20.20 edgenode=true

确认节点 label 是否设置成功

kubectl get nodes -l ‘label_key=label_value’

获取 statefulset

kubectl get statefulset

删除 statefulsets

[root@xiexianbin_cn ~]# kubectl get statefulsets
NAME            DESIRED   CURRENT   AGE
mariadb   2         2         1d
[root@xiexianbin_cn ~]# kubectl delete statefulsets mariadb
statefulset "mariadb" deleted
kubectl delete statefulsets mariadb -n openstack --force

弹性伸缩

# kubectl scale --replicas=3 deployment nginx-dp
deployment.apps/nginx-dp scaled
# kubectl describe svc/nginx-dp
Name:              nginx-dp
Namespace:         default
Labels:            app=nginx-dp
Annotations:       <none>
Selector:          app=nginx-dp
Type:              ClusterIP
IP:                10.116.6.228
Port:              80-80  80/TCP
TargetPort:        80/TCP
Endpoints:         10.112.0.7:80,10.112.1.9:80,10.112.2.7:80
Session Affinity:  None
Events:            <none>

autoscale

kubectl autoscale deployment nginx-deployment --min=10 --max=15 --cpu-percent=80

rollout

# 查看 rollout 情况
kubectl rollout status deployment
kubectl rollout status deployment nginx-deployment

# 查看历史
kubectl rollout history

# 回滚
kubectl rollout undo deployment/nginx-deployment

# 暂停更新,仅创建新 pod ,不执行删除动作
kubectl rollout pause deployment/nginx-deployment
# 继续更新,执行删除动作
kubectl rollout resume deployment/nginx-deployment

YAML 文件

快速编写 YAML

  • kubectl run 生成模板
kubectl create deployment nginx --image=nginx:latest -o yaml --dry-run=client > nginx-deploy.yaml
  • kubectl get 导出已有应用模板
kubectl get my-deploy/nginx -o yaml --export  > my-deploy.yaml

create/apply

kubectl create -f a.yaml
kubectl apply -f a.yaml
kubectl replace -f a.yaml

其他工具

本文总阅读量 次 本站总访问量 次 本站总访客数