kubectl - 常用命令
配置kubeconfig
默认情况下, kubectl 在 $HOME/.kube 目录下查找名为 config 的文件。 你可以通过设置 KUBECONFIG 环境变量或者设置 --kubeconfig (opens new window) 参数来指定其他 kubeconfig 文件。
# 通过环境变量
export KUBECONFIG=/path/to/.kube/config
# 通过命令行参数
kubectl ... --kubeconfig=/path/to/.kube/config
# 声明式配置
参考:使用配置文件对 Kubernetes 对象进行声明式管理 | Kubernetes (opens new window)
# 应用
无论 创建 或是 更新 都可以使用
kubectl apply -f xxxx.yaml
# 删除
kubectl delete -f xxxx.yaml
# Node
# 列表
kubectl get nodes
# Pod
# 列表
运行中的应用在 docker 里面叫容器,在 k8s 里面叫 Pod
kubectl get pods -A
# 详情
kubectl describe pod <Pod name>
# 进入
kubectl exec -it <Pod name> -- /bin/bash
# 指令式
# 删除
# 删除此命名空间下所有的pod
kubectl delete --all pods -n <命名空间>
# 强制删除
kubectl delete pods <pod> --grace-period=0 --force
# 端口转发
kubectl port-forward --namespace <命名空间> svc/<服务名> <服务端口>:<本机端口>
# kubectl port-forward --namespace common svc/rabbitmq 15672:15672
# 场景
# 查询 Pod CPU 占用情况
# 安装metrics-server
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# 编辑,跳过tls检查
kubectl -n kube-system edit deployment metrics-server
spec:
spec:
containers:
- args:
# 添加以下两行内容
- --kubelet-insecure-tls
- --kubelet-preferred-address-types=InternalIP
:wq 等待新 pod 部署完成
kubectl top pods -A | sort -k3 -nr
# 查看 Requests 最高的 Pod 列表
kubectl get pods -A -o json | jq -r '
.items[] |
.metadata.namespace as $ns |
.metadata.name as $name |
.spec.containers[] |
select(.resources.requests.cpu != null) |
"\($ns)\t\($name)\t\(.name)\t\(.resources.requests.cpu)"
' | sort -k4 -hr | head -n 20
# 传输文件到 PVC
- 操作前确保 pvc 没有挂载到 pod
- 挂载要操作的 pvc 到调试 pod
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: pvc-toolbox
spec:
containers:
- name: toolbox
image: busybox
command: ["sleep", "36000"]
volumeMounts:
- mountPath: /data
name: target
volumes:
- name: target
persistentVolumeClaim:
claimName: <pvc-name>
EOF
- 进入 Pod 检查文件路径
kubectl exec -it pvc-toolbox -- /bin/sh
- 复制文件:
# local -> pvc
kubectl cp ./mydata.sql pvc-toolbox:/data/mydata.sql
kubectl cp . pvc-toolbox:/data/data # 复制当前目录到/data/data (不支持./*)
# pvc -> local
kubectl cp pvc-toolbox:/data/mydata.sql ./mydata.sql
- 删除调试 Pod:
kubectl delete pod pvc-toolbox
上次更新: 2025/12/13, 03:39:12