kubectl命令行工具 #

一、kubectl概述 #

kubectl是Kubernetes的命令行工具,用于与Kubernetes集群进行交互。通过kubectl,你可以部署应用、检查和管理集群资源、查看日志等。

1.1 命令语法 #

bash
kubectl [command] [TYPE] [NAME] [flags]
组成部分 说明 示例
command 操作命令 get、create、delete、apply
TYPE 资源类型 pod、deployment、service
NAME 资源名称 nginx-app、my-service
flags 命令标志 -n、-o、–all-namespaces

1.2 命令分类 #

text
kubectl命令分类
    │
    ├── 基础命令
    │   ├── create ─── 创建资源
    │   ├── get ─── 查看资源
    │   ├── delete ─── 删除资源
    │   └── apply ─── 应用配置
    │
    ├── 部署命令
    │   ├── rollout ─── 滚动更新管理
    │   ├── scale ─── 扩缩容
    │   └── autoscale ─── 自动扩缩容
    │
    ├── 集群管理
    │   ├── cluster-info ─── 集群信息
    │   ├── top ─── 资源使用
    │   └── cordon/uncordon ─── 节点调度
    │
    └── 调试命令
        ├── describe ─── 详细信息
        ├── logs ─── 查看日志
        ├── exec ─── 执行命令
        └── port-forward ─── 端口转发

二、基础命令 #

2.1 kubectl get - 查看资源 #

bash
# 查看Pod
kubectl get pods
kubectl get pod
kubectl get po

# 查看所有命名空间的Pod
kubectl get pods -A
kubectl get pods --all-namespaces

# 查看指定命名空间
kubectl get pods -n kube-system

# 查看更多信息
kubectl get pods -o wide

# 查看标签
kubectl get pods --show-labels

# 按标签筛选
kubectl get pods -l app=nginx

# 查看多种资源
kubectl get pods,svc,deploy

# 输出格式
kubectl get pods -o yaml
kubectl get pods -o json
kubectl get pods -o name
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

# 查看特定资源
kubectl get pod nginx-app-xxx -o yaml

2.2 kubectl describe - 查看详情 #

bash
# 查看Pod详情
kubectl describe pod <pod-name>

# 查看Node详情
kubectl describe node <node-name>

# 查看Deployment详情
kubectl describe deployment <deployment-name>

# 查看Service详情
kubectl describe service <service-name>

2.3 kubectl create - 创建资源 #

bash
# 创建Deployment
kubectl create deployment nginx --image=nginx

# 创建Service
kubectl create service clusterip nginx --tcp=80:80

# 创建命名空间
kubectl create namespace my-namespace

# 创建ConfigMap
kubectl create configmap my-config --from-literal=key1=value1

# 创建Secret
kubectl create secret generic my-secret --from-literal=password=123456

# 从文件创建
kubectl create -f deployment.yaml

2.4 kubectl apply - 应用配置 #

bash
# 应用单个文件
kubectl apply -f deployment.yaml

# 应用多个文件
kubectl apply -f deployment.yaml -f service.yaml

# 应用目录下所有文件
kubectl apply -f ./k8s/

# 从URL应用
kubectl apply -f https://raw.githubusercontent.com/.../deployment.yaml

# 使用kustomize
kubectl apply -k ./kustomize/

2.5 kubectl delete - 删除资源 #

bash
# 删除Pod
kubectl delete pod <pod-name>

# 删除Deployment
kubectl delete deployment <deployment-name>

# 删除Service
kubectl delete service <service-name>

# 从文件删除
kubectl delete -f deployment.yaml

# 按标签删除
kubectl delete pods -l app=nginx

# 删除命名空间下所有Pod
kubectl delete pods --all -n my-namespace

# 强制删除
kubectl delete pod <pod-name> --force --grace-period=0

三、部署管理命令 #

3.1 kubectl rollout - 滚动更新 #

bash
# 查看滚动更新状态
kubectl rollout status deployment/nginx

# 查看滚动更新历史
kubectl rollout history deployment/nginx

# 查看特定版本详情
kubectl rollout history deployment/nginx --revision=2

# 回滚到上一版本
kubectl rollout undo deployment/nginx

# 回滚到特定版本
kubectl rollout undo deployment/nginx --to-revision=2

# 暂停滚动更新
kubectl rollout pause deployment/nginx

# 恢复滚动更新
kubectl rollout resume deployment/nginx

# 重启Deployment
kubectl rollout restart deployment/nginx

3.2 kubectl scale - 扩缩容 #

bash
# 扩容到指定副本数
kubectl scale deployment/nginx --replicas=5

# 条件扩容
kubectl scale deployment/nginx --current-replicas=3 --replicas=5

# 多资源扩容
kubectl scale deployment/nginx deployment/apache --replicas=3

3.3 kubectl autoscale - 自动扩缩容 #

bash
# 创建HPA
kubectl autoscale deployment/nginx --min=2 --max=10 --cpu-percent=80

# 查看HPA
kubectl get hpa

# 删除HPA
kubectl delete hpa nginx

3.4 kubectl set - 更新配置 #

bash
# 更新镜像
kubectl set image deployment/nginx nginx=nginx:1.26

# 更新环境变量
kubectl set env deployment/nginx ENV=production

# 更新资源限制
kubectl set resources deployment/nginx --limits=cpu=200m,memory=256Mi

# 更新Service选择器
kubectl set selector service/nginx app=nginx

四、集群管理命令 #

4.1 kubectl cluster-info - 集群信息 #

bash
# 查看集群信息
kubectl cluster-info

# 查看集群详情
kubectl cluster-info dump

# 查看集群版本
kubectl version

# 查看API版本
kubectl api-versions

# 查看资源类型
kubectl api-resources

4.2 kubectl top - 资源监控 #

bash
# 查看节点资源使用
kubectl top nodes

# 查看Pod资源使用
kubectl top pods

# 查看指定命名空间
kubectl top pods -n kube-system

# 按资源使用排序
kubectl top pods --sort-by=memory

4.3 kubectl cordon/uncordon - 节点调度 #

bash
# 标记节点不可调度
kubectl cordon <node-name>

# 恢复节点调度
kubectl uncordon <node-name>

# 驱逐节点上的Pod
kubectl drain <node-name>

# 忽略DaemonSet
kubectl drain <node-name> --ignore-daemonsets

# 强制驱逐
kubectl drain <node-name> --force --ignore-daemonsets --delete-emptydir-data

4.4 kubectl taint - 节点污点 #

bash
# 添加污点
kubectl taint nodes <node-name> key=value:NoSchedule

# 删除污点
kubectl taint nodes <node-name> key:NoSchedule-

# 查看污点
kubectl describe node <node-name> | grep Taints

4.5 kubectl label - 标签管理 #

bash
# 添加标签
kubectl label pod <pod-name> env=production

# 修改标签
kubectl label pod <pod-name> env=staging --overwrite

# 删除标签
kubectl label pod <pod-name> env-

# 查看标签
kubectl get pods --show-labels

五、调试命令 #

5.1 kubectl logs - 查看日志 #

bash
# 查看Pod日志
kubectl logs <pod-name>

# 实时查看日志
kubectl logs -f <pod-name>

# 查看最近N行日志
kubectl logs --tail=100 <pod-name>

# 查看最近时间日志
kubectl logs --since=1h <pod-name>

# 查看之前容器的日志
kubectl logs --previous <pod-name>

# 多容器Pod指定容器
kubectl logs <pod-name> -c <container-name>

# 查看所有容器日志
kubectl logs <pod-name> --all-containers

# 输出到文件
kubectl logs <pod-name> > app.log

5.2 kubectl exec - 执行命令 #

bash
# 进入容器交互
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -- /bin/sh

# 执行单个命令
kubectl exec <pod-name> -- ls /app

# 指定容器
kubectl exec <pod-name> -c <container-name> -- ls /app

# 从文件执行脚本
cat script.sh | kubectl exec -i <pod-name> -- /bin/sh

5.3 kubectl port-forward - 端口转发 #

bash
# 转发Pod端口
kubectl port-forward <pod-name> 8080:80

# 转发Service端口
kubectl port-forward svc/<service-name> 8080:80

# 转发Deployment端口
kubectl port-forward deployment/<deployment-name> 8080:80

# 本地地址绑定
kubectl port-forward <pod-name> 127.0.0.1:8080:80

# 多端口转发
kubectl port-forward <pod-name> 8080:80 8443:443

5.4 kubectl cp - 文件复制 #

bash
# 复制本地文件到Pod
kubectl cp ./local-file.txt <pod-name>:/remote/path/

# 从Pod复制文件到本地
kubectl cp <pod-name>:/remote/file.txt ./local-file.txt

# 指定命名空间
kubectl cp ./file.txt <namespace>/<pod-name>:/path/

# 指定容器
kubectl cp ./file.txt <pod-name>:/path/ -c <container-name>

5.5 kubectl debug - 调试Pod #

bash
# 创建调试容器
kubectl debug <pod-name> -it --image=busybox

# 复制Pod调试
kubectl debug <pod-name> -it --copy-to=debug-pod --image=busybox

# 节点调试
kubectl debug node/<node-name> -it --image=busybox

六、配置管理命令 #

6.1 kubectl config - 配置管理 #

bash
# 查看配置
kubectl config view

# 查看当前上下文
kubectl config current-context

# 查看集群列表
kubectl config get-clusters

# 查看上下文列表
kubectl config get-contexts

# 切换上下文
kubectl config use-context <context-name>

# 设置集群
kubectl config set-cluster <cluster-name> --server=<server-url>

# 设置用户
kubectl config set-credentials <user-name> --token=<token>

# 设置上下文
kubectl config set-context <context-name> --cluster=<cluster> --user=<user>

# 删除上下文
kubectl config delete-context <context-name>

6.2 kubectl create configmap #

bash
# 从字面值创建
kubectl create configmap my-config --from-literal=key1=value1 --from-literal=key2=value2

# 从文件创建
kubectl create configmap my-config --from-file=config.properties

# 从目录创建
kubectl create configmap my-config --from-file=./config-dir/

# 从env文件创建
kubectl create configmap my-config --from-env-file=config.env

6.3 kubectl create secret #

bash
# 创建通用Secret
kubectl create secret generic my-secret --from-literal=password=123456

# 从文件创建
kubectl create secret generic my-secret --from-file=ssh-private-key=~/.ssh/id_rsa

# 创建TLS Secret
kubectl create secret tls my-tls --cert=path/to/cert.crt --key=path/to/cert.key

# 创建docker-registry Secret
kubectl create secret docker-registry my-registry \
  --docker-server=<registry-server> \
  --docker-username=<username> \
  --docker-password=<password> \
  --docker-email=<email>

七、高级命令 #

7.1 kubectl patch - 更新资源 #

bash
# 使用JSON补丁
kubectl patch deployment nginx -p '{"spec":{"replicas":3}}'

# 使用策略合并补丁
kubectl patch deployment nginx --type='merge' -p '{"spec":{"replicas":3}}'

# 从文件补丁
kubectl patch deployment nginx --patch-file=patch.yaml

7.2 kubectl edit - 编辑资源 #

bash
# 编辑Deployment
kubectl edit deployment nginx

# 编辑Service
kubectl edit svc nginx

# 使用指定编辑器
KUBE_EDITOR=nano kubectl edit deployment nginx

# 输出格式编辑
kubectl edit deployment nginx -o yaml

7.3 kubectl wait - 等待条件 #

bash
# 等待Pod就绪
kubectl wait --for=condition=ready pod -l app=nginx

# 等待Pod删除
kubectl wait --for=delete pod <pod-name>

# 等待超时
kubectl wait --for=condition=ready pod -l app=nginx --timeout=300s

7.4 kubectl explain - 资源说明 #

bash
# 查看资源字段说明
kubectl explain pod

# 查看嵌套字段
kubectl explain pod.spec

# 查看深层字段
kubectl explain pod.spec.containers

八、输出格式 #

8.1 输出格式选项 #

bash
# YAML格式
kubectl get pod <pod-name> -o yaml

# JSON格式
kubectl get pod <pod-name> -o json

# JSON路径
kubectl get pods -o jsonpath='{.items[*].metadata.name}'

# 自定义列
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

# 仅名称
kubectl get pods -o name

# 宽输出
kubectl get pods -o wide

8.2 常用JSON路径 #

bash
# 获取所有Pod名称
kubectl get pods -o jsonpath='{.items[*].metadata.name}'

# 获取所有Pod IP
kubectl get pods -o jsonpath='{.items[*].status.podIP}'

# 获取特定标签的Pod
kubectl get pods -o jsonpath='{.items[?(@.metadata.labels.app=="nginx")].metadata.name}'

# 获取容器镜像
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'

九、实用技巧 #

9.1 别名设置 #

bash
# 添加到 ~/.bashrc 或 ~/.zshrc
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias ka='kubectl apply -f'
alias kl='kubectl logs'
alias ke='kubectl exec -it'
alias kpf='kubectl port-forward'

# 完整别名示例
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deploy'
alias kgpw='kubectl get pods -w'
alias kgsw='kubectl get svc -w'

9.2 自动补全 #

bash
# Bash自动补全
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc

# Zsh自动补全
source <(kubectl completion zsh)
echo "source <(kubectl completion zsh)" >> ~/.zshrc

# 为别名添加补全
complete -F __start_kubectl k

9.3 命令速查表 #

场景 命令
快速查看所有资源 kubectl get all
查看资源使用情况 kubectl top nodes
查看Pod事件 kubectl describe pod <name> | grep -A 10 Events
快速删除所有Pod kubectl delete pods --all
查看资源定义 kubectl explain pod.spec
导出资源YAML kubectl get <resource> <name> -o yaml --export

十、总结 #

10.1 常用命令速查 #

类别 命令
查看 getdescribe
创建 createapply
更新 editpatchset
删除 delete
调试 logsexecport-forward
部署 rolloutscaleautoscale
集群 cluster-infotopcordon

10.2 下一步 #

掌握了kubectl的基本使用后,让我们深入学习 架构概述,理解Kubernetes的内部工作机制。

最后更新:2026-03-28