一、kubectl 简介
1.1 什么是 kubectl
kubectl 是 Kubernetes 官方提供的命令行客户端工具,允许用户通过命令行与 Kubernetes API Server 进行交互,从而实现对集群资源的管理。
1.2 kubectl 的作用
- 资源管理:创建、更新、删除各类 Kubernetes 资源(Pod、Deployment、Service 等)
- 应用部署:将容器化应用部署到集群中
- 集群监控:查看集群状态、节点信息、资源使用情况
- 故障排查:查看日志、进入容器、执行调试命令
- 配置管理:管理 kubeconfig、切换集群上下文
1.3 架构位置
plaintext
┌─────────────────────────────────────────────────────────────────┐
│ kubectl 客户端 │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ kubectl CLI 工具 │ │
│ │ • 命令行解析 │ │
│ │ • 配置加载 (kubeconfig) │ │
│ │ • API 请求构建 │ │
│ └──────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
│ HTTPS/REST API
▼
┌─────────────────────────────────────────────────────────────────┐
│ Kubernetes API Server │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ Core API │ │ Apps API │ │ Net API │ │ Auth API │ │
│ │ (v1) │ │ (apps/v1) │ │ (networking)│ │ (rbac) │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Worker 1 │ │ Worker 2 │ │ Worker 3 │
│ ┌─────────┐ │ │ ┌─────────┐ │ │ ┌─────────┐ │
│ │ Pod A │ │ │ │ Pod B │ │ │ │ Pod C │ │
│ └─────────┘ │ │ └─────────┘ │ │ └─────────┘ │
└───────────────┘ └───────────────┘ └───────────────┘
1.4 基本语法
bash
kubectl [command] [TYPE] [NAME] [flags]
参数说明:
| 参数 | 说明 |
|---|---|
command |
操作命令,如 get、create、delete、apply |
TYPE |
资源类型,如 pod、deployment、service、namespace |
NAME |
资源名称,可省略(对所有资源生效)或使用正则匹配 |
flags |
特殊标志,如 -n(命名空间)、-o(输出格式) |
二、安装与配置
2.1 多种安装方式
方式一:使用包管理器安装
Linux (Ubuntu/Debian):
bash
# 添加阿里云镜像源
curl -fsSL https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /usr/share/keyrings/kubernetes-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://mirrors.aliyun.com/kubernetes/apt kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list
# 安装 kubectl
sudo apt-get update
sudo apt-get install -y kubectl
# 验证安装
kubectl version --client
macOS (Homebrew):
bash
# 安装
brew install kubectl
# 或升级
brew upgrade kubectl
# 验证
kubectl version --client
方式二:使用 curl 直接下载(跨平台)
bash
# 下载最新版本(Linux)
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
# 下载指定版本(如 1.31.0)
curl -LO "https://dl.k8s.io/release/v1.31.0/bin/linux/amd64/kubectl"
# 添加执行权限
chmod +x kubectl
# 移动到系统路径
sudo mv kubectl /usr/local/bin/
# 验证
kubectl version --client
方式三:使用阿里云镜像
bash
# 使用阿里云镜像下载
curl -LO "https://mirrors.aliyun.com/kubernetes/release/v1.31.0/bin/linux/amd64/kubectl"
chmod +x kubectl
sudo mv kubectl /usr/local/bin/
2.2 kubeconfig 配置详解
kubeconfig 文件是 kubectl 的配置文件,用于管理多集群访问凭证。
2.2.1 默认配置文件位置
plaintext
~/.kube/config
2.2.2 kubeconfig 文件结构
yaml
# ~/.kube/config
apiVersion: v1
kind: Config
clusters: # 集群定义
- name: production-cluster
cluster:
server: https://api.production.example.com:6443
certificate-authority-data: <base64编码的CA证书>
- name: dev-cluster
cluster:
server: https://api.dev.example.com:6443
certificate-authority-data: <base64编码的CA证书>
# 跳过证书验证(仅用于测试)
insecure-skip-tls-verify: false
users: # 用户凭证
- name: admin-user
user:
client-certificate-data: <base64编码的客户端证书>
client-key-data: <base64编码的客户端私钥>
# 或使用 Token
token: <your-token>
- name: readonly-user
user:
token: <readonly-token>
contexts: # 上下文(集群+用户+命名空间组合)
- name: prod-admin
context:
cluster: production-cluster
user: admin-user
namespace: production
- name: dev-readonly
context:
cluster: dev-cluster
user: readonly-user
namespace: default
current-context: prod-admin # 当前使用的上下文
2.2.3 使用 kubectl config 命令管理配置
bash
# 查看当前配置
kubectl config view
# 查看当前上下文
kubectl config current-context
# 列出所有上下文
kubectl config get-contexts
# 切换上下文
kubectl config use-context prod-admin
# 设置默认命名空间
kubectl config set-context --current --namespace=my-namespace
# 添加新集群
kubectl config set-cluster my-cluster \
--server=https://api.example.com:6443 \
--certificate-authority=/path/to/ca.crt
# 添加用户凭证(基于证书)
kubectl config set-credentials my-user \
--client-certificate=/path/to/client.crt \
--client-key=/path/to/client.key
# 添加 Token 凭证
kubectl config set-credentials my-user --token=<your-token>
# 创建新上下文
kubectl config set-context my-context \
--cluster=my-cluster \
--user=my-user \
--namespace=my-namespace
# 删除配置项
kubectl config unset users.my-user
kubectl config delete-context my-context
2.3 多集群管理
多集群切换场景
在实际工作中,我们通常需要管理多个 Kubernetes 集群:
plaintext
┌────────────────────────────────────────────────────────┐
│ ~/.kube/config │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 生产集群 │ │ 测试集群 │ │ 开发集群 │ │
│ │ production │ │ testing │ │ dev │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ 当前: production (生产集群) │
└────────────────────────────────────────────────────────┘
多集群切换操作
bash
# 快速切换集群
alias kc='kubectl config use-context'
# 查看所有集群
kubectl config get-contexts -o name
# 一键切换(假设有这些上下文)
kubectl config use-context production
kubectl config use-context staging
kubectl config use-context dev
使用 KUBECONFIG 环境变量
bash
# 指定多个 kubeconfig 文件
export KUBECONFIG=~/.kube/config:/path/to/cluster2.yaml:/path/to/cluster3.yaml
# 合并查看所有配置
kubectl config view --flatten
# 保存合并后的配置
kubectl config view --flatten > ~/.kube/config-merged
三、核心概念
3.1 Kubernetes 资源对象
Kubernetes 中的所有内容都被抽象为"资源对象",主要包括:
| 资源类型 | 说明 | 缩写 |
|---|---|---|
| Pod | 最小调度单位,包含一个或多个容器 | po |
| Deployment | 无状态应用部署 | deploy |
| ReplicaSet | Pod 副本管理 | rs |
| StatefulSet | 有状态应用部署 | sts |
| DaemonSet | 节点守护进程 | ds |
| Service | 服务发现与负载均衡 | svc |
| ConfigMap | 配置管理 | cm |
| Secret | 敏感信息管理 | secret |
| PersistentVolumeClaim | 持久化存储 | pvc |
| Namespace | 隔离环境 | ns |
| Node | 工作节点 | no |
| ServiceAccount | 服务账号 | sa |
| Role/ClusterRole | RBAC 角色 | - |
| RoleBinding/ClusterRoleBinding | RBAC 绑定 | - |
| Ingress | HTTP 路由规则 | ing |
| CronJob | 定时任务 | cj |
| Job | 一次性任务 | - |
| Endpoint | 服务端点 | ep |
| Event | 集群事件 | ev |
查看所有支持的资源类型
bash
# 查看集群支持的所有资源类型
kubectl api-resources
# 输出示例
NAME SHORTNAMES APIVERSION NAMESPACED KIND
componentstatuses cs v1 false ComponentStatus
configmaps cm v1 true ConfigMap
endpoints ep v1 true Endpoints
namespaces ns v1 false Namespace
nodes no v1 false Node
pods po v1 true Pod
secrets v1 true Secret
services svc v1 true Service
...
3.2 命名空间(Namespace)
命名空间是 Kubernetes 中最重要的资源隔离机制。
plaintext
┌─────────────────────────────────────────────────────────────┐
│ Kubernetes Cluster │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────┐ │
│ │ production │ │ staging │ │ dev │ │
│ │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌─────────┐ │ │
│ │ │Deployment │ │ │ │Deployment │ │ │ │Deployment│ │ │
│ │ │ Service │ │ │ │ Service │ │ │ │ Service │ │ │
│ │ │ ConfigMap │ │ │ │ ConfigMap │ │ │ │ ConfigMap│ │ │
│ │ └───────────┘ │ │ └───────────┘ │ │ └─────────┘ │ │
│ └─────────────────┘ └─────────────────┘ └─────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ kube-system (系统命名空间) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘
命名空间操作
bash
# 查看所有命名空间
kubectl get namespaces
# 输出示例
NAME STATUS AGE
default Active 30d
kube-node-lease Active 30d
kube-public Active 30d
kube-system Active 30d
production Active 15d
staging Active 20d
dev Active 25d
# 创建命名空间
kubectl create namespace my-app
# 使用 YAML 创建
kubectl create -f - <<EOF
apiVersion: v1
kind: Namespace
metadata:
name: my-app
labels:
environment: production
team: platform
EOF
# 切换默认命名空间
kubectl config set-context --current --namespace=my-app
# 在指定命名空间执行操作
kubectl get pods -n my-app
kubectl get pods --all-namespaces # 查看所有命名空间
kubectl get pods -A # -A 是 --all-namespaces 的简写
# 删除命名空间(会删除命名空间内所有资源)
kubectl delete namespace my-app
3.3 标签与选择器
标签(Labels)是附着在资源对象上的键值对,用于组织和选择资源。
plaintext
┌──────────────────────────────────────────────────────────────┐
│ Pod Example │
│ metadata: │
│ labels: │
│ app: nginx ← 环境标签 │
│ version: v1.0 ← 版本标签 │
│ tier: frontend ← 层级标签 │
│ team: platform ← 团队标签 │
└──────────────────────────────────────────────────────────────┘
标签操作
bash
# 创建带标签的资源
kubectl run nginx --image=nginx:1.21 --labels="app=nginx,tier=frontend"
# 为已有资源添加标签
kubectl label pods nginx-pod environment=production team=backend
# 更新标签
kubectl label pods nginx-pod version=v2.0 --overwrite
# 删除标签
kubectl label pods nginx-pod team-
# 查看资源标签
kubectl get pods --show-labels
# 输出示例
NAME READY STATUS RESTARTS AGE LABELS
nginx 1/1 Running 0 5d app=nginx,tier=frontend
redis 1/1 Running 0 10d app=redis,tier=cache
# 按标签筛选
kubectl get pods -l app=nginx
kubectl get pods -l 'app in (nginx,redis)'
kubectl get pods -l 'tier=frontend,environment=production'
kubectl get pods -l 'app!=nginx'
# 查找同时满足多个条件
kubectl get pods -l 'app=nginx && tier=frontend'
# 使用表达式
kubectl get pods -l 'environment in (production,staging),tier notin (frontend)'
四、常用命令详解
4.1 资源查看命令
4.1.1 kubectl get - 列出资源
bash
# 基本语法
kubectl get <resource-type> [resource-name] [flags]
# 查看所有 Pod
kubectl get pods
# 输出示例
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-7x4pq 1/1 Running 0 10d
redis-7d6f8b4c5-9t2mn 1/1 Running 0 15d
api-gateway-5b9c7d6f8-m4k 2/2 Running 0 7d
# 查看所有类型的资源
kubectl get all
# 查看特定资源
kubectl get pod nginx-6799fc88d8-7x4pq
kubectl get service my-service
kubectl get deployment my-app
# 查看多种资源
kubectl get pods,services,deployments
kubectl get po,svc,deploy
# 列出所有命名空间的资源
kubectl get pods --all-namespaces
kubectl get pods -A
# 查看资源更详细的信息
kubectl get pods -o wide
# 输出示例
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE
nginx 1/1 Running 0 10d 10.244.1.5 worker-1 <none>
# 查看标签
kubectl get pods --show-labels
# 按标签过滤
kubectl get pods -l app=nginx
kubectl get pods -l 'app=nginx,tier=frontend'
# 实时监听资源变化(类似 watch)
kubectl get pods --watch
kubectl get pods -w
# 只显示资源名称
kubectl get pods -o name
# 输出: pod/nginx-6799fc88d8-7x4pq
# 使用自定义列
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
# 使用 JSONPath 提取特定字段
kubectl get pods nginx -o jsonpath='{.status.podIP}'
# 输出: 10.244.1.5
# 列出所有节点
kubectl get nodes
# 查看节点状态详情
kubectl get nodes -o wide
# 查看节点污点/标签
kubectl get nodes --show-labels
# 查看资源数量
kubectl get pods --all-namespaces --no-headers | wc -l
4.1.2 kubectl describe - 查看资源详情
bash
# 查看 Pod 详细描述
kubectl describe pod nginx-6799fc88d8-7x4pq
# 输出示例(截取关键部分)
Name: nginx-6799fc88d8-7x4pq
Namespace: default
Priority: 0
Node: worker-1/192.168.1.101
Start Time: Mon, 01 Jan 2024 10:00:00 +0000
Labels: app=nginx
pod-template-hash=6799fc88d8
Annotations: <none>
Status: Running
IP: 10.244.1.5
IPs:
IP: 10.244.1.5
Controlled By: ReplicaSet/nginx-6799fc88d8
Containers:
nginx:
Container ID: docker://abc123...
Image: nginx:1.21
Port: 80/TCP
State: Running
Ready: True
Restart Count: 0
Limits:
cpu: 500m
memory: 256Mi
Requests:
cpu: 100m
memory: 128Mi
Environment: <none>
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Events: <none>
# 查看 Node 详细信息(包含调度信息)
kubectl describe node worker-1
# 查看 Service 详细信息
kubectl describe service my-service
# 查看 Deployment 详细信息
kubectl describe deployment my-app
# 查看命名空间下所有资源
kubectl describe namespace production
# 使用简短语法
kubectl desc po nginx
kubectl desc svc my-service
4.1.3 kubectl logs - 查看日志
bash
# 查看 Pod 日志
kubectl logs nginx-pod
# 实时跟踪日志
kubectl logs -f nginx-pod
# 查看最近 100 行日志
kubectl logs --tail=100 nginx-pod
# 查看指定时间范围的日志
kubectl logs --since=1h nginx-pod
kubectl logs --since=2024-01-01T00:00:00Z nginx-pod
# 查看上一个终止容器的日志(容器重启后)
kubectl logs --previous nginx-pod
# 多容器 Pod - 指定容器
kubectl logs nginx-pod -c nginx-container
kubectl logs nginx-pod --container nginx-container
# 所有容器日志
kubectl logs nginx-pod --all-containers=true
# 标签选择器 - 查看匹配标签的所有 Pod 日志
kubectl logs -l app=nginx
# 输出带时间戳
kubectl logs --timestamps nginx-pod
# 结合 tail 和 follow
kubectl logs -f --tail=200 nginx-pod
4.1.4 kubectl explain - 查看资源文档
bash
# 查看 Pod 资源结构
kubectl explain pods
# 输出示例(截取)
KIND: Pod
VERSION: v1
DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.
FIELDS:
apiVersion <string>
kind <string>
metadata <Object>
spec <Object>
status <Object>
# 查看具体字段定义
kubectl explain pods.spec
kubectl explain pods.spec.containers
kubectl explain pods.spec.containers.resources
# 递归查看所有字段
kubectl explain pods --recursive
# 查看 Deployment 定义
kubectl explain deployment
kubectl explain deployment.spec
kubectl explain deployment.spec.selector
4.2 资源创建与删除命令
4.2.1 kubectl create - 创建资源
bash
# 从 YAML 文件创建资源
kubectl create -f pod.yaml
kubectl create -f ./manifests/
# 多个文件
kubectl create -f pod.yaml -f service.yaml
# 标准输入
cat pod.yaml | kubectl create -f -
# 创建 Deployment
kubectl create deployment nginx --image=nginx:1.21
# 创建带副本数的 Deployment
kubectl create deployment redis --image=redis:7 --replicas=3
# 创建命名空间
kubectl create namespace my-app
# 创建 ConfigMap
kubectl create configmap app-config --from-literal=key1=value1 --from-literal=key2=value2
kubectl create configmap app-config --from-file=config.properties
# 从文件创建 ConfigMap
kubectl create configmap nginx-config --from-file=nginx.conf
# 创建 Secret
kubectl create secret generic my-secret --from-literal=password=secret123
kubectl create secret tls my-tls --cert=tls.crt --key=tls.key
# 创建 Service(ClusterIP 类型)
kubectl expose deployment nginx --port=80 --target-port=8080
# 创建 NodePort 类型 Service
kubectl expose deployment nginx --port=80 --target-port=8080 --type=NodePort
# 创建 LoadBalancer 类型 Service
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# 模拟运行(不真正创建)
kubectl create -f pod.yaml --dry-run=client
# 服务端模拟运行
kubectl create -f pod.yaml --dry-run=server
# 记录命令(用于回滚)
kubectl create -f deployment.yaml --record
# 查看 YAML 输出(不创建)
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml
4.2.2 kubectl apply - 声明式创建/更新
bash
# 声明式创建或更新(推荐)
kubectl apply -f pod.yaml
# 目录递归应用
kubectl apply -f ./manifests/
kubectl apply -f ./manifests/ -R
# 查看将要应用的变更(diff)
kubectl diff -f pod.yaml
# 查看 apply 预览
kubectl apply -f pod.yaml --dry-run=server -o yaml
# 查看历史配置
kubectl apply view-last-applied -f pod.yaml
# 设置最后应用的注解
kubectl apply set-last-applied -f pod.yaml
# 标签注解管理
kubectl apply edit-last-applied -f pod.yaml
# 验证文件语法
kubectl apply -f pod.yaml --validate=true
# Prune(清理不在文件中的资源)
kubectl apply -f ./manifests/ --prune -l app=myapp
# 服务端应用(不等待完成)
kubectl apply -f pod.yaml --server-side
4.2.3 kubectl delete - 删除资源
bash
# 删除 Pod
kubectl delete pod nginx-pod
# 按标签删除
kubectl delete pods -l app=nginx
# 删除所有 Pod
kubectl delete pods --all
# 从 YAML 删除
kubectl delete -f pod.yaml
# 删除所有资源
kubectl delete all --all
# 删除命名空间(会删除所有资源)
kubectl delete namespace my-namespace
# 删除已终止的 Pod
kubectl delete pods --field-selector=status.phase=Failed
# 删除所有已完成的 Job
kubectl delete jobs --all
# 优雅删除(等待资源终止)
kubectl delete pod nginx --grace-period=30
# 强制删除(立即终止)
kubectl delete pod nginx --grace-period=0 --force
# 删除前确认
kubectl delete pod nginx --dry-run=client
4.2.4 kubectl replace - 替换资源
bash
# 替换资源(完全替换)
kubectl replace -f pod.yaml
# 强制替换(先删除再创建)
kubectl replace --force -f pod.yaml
# 从标准输入替换
cat pod.yaml | kubectl replace -f -
# 替换状态(用于某些特殊资源)
kubectl replace --subresource=status -f deployment.yaml
4.3 资源编辑与更新命令
4.3.1 kubectl edit - 在线编辑
bash
# 编辑 Deployment
kubectl edit deployment nginx
# 使用指定编辑器
KUBE_EDITOR="vim" kubectl edit deployment nginx
# 编辑并保存为新文件
kubectl edit deployment nginx -o yaml > edited.yaml
# 只读模式(不保存)
kubectl edit deployment nginx --dry-run=client -o yaml
# 编辑特定容器
kubectl edit deployment nginx -c nginx
# 强制编辑(绕过验证)
kubectl edit deployment nginx --validate=false
4.3.2 kubectl patch - 打补丁
bash
# JSON Patch - 修改副本数
kubectl patch deployment nginx -p '{"spec":{"replicas":5}}'
# Strategic Merge Patch - 修改镜像
kubectl patch deployment nginx --type='strategic' -p '[
{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"nginx:1.22"}
]'
# 修改标签
kubectl patch pod nginx -p '{"metadata":{"labels":{"version":"v2"}}}'
# 添加注解
kubectl patch service nginx -p '{"metadata":{"annotations":{"prometheus.io/scrape":"true"}}}'
# 修改服务类型
kubectl patch service nginx -p '{"spec":{"type":"LoadBalancer"}}'
# 修改资源限制
kubectl patch deployment nginx -p '{
"spec": {
"template": {
"spec": {
"containers": [{
"name": "nginx",
"resources": {
"limits": {"memory": "512Mi", "cpu": "500m"},
"requests": {"memory": "256Mi", "cpu": "100m"}
}
}]
}
}
}
}'
# 使用 YAML 格式
kubectl patch deployment nginx --patch-file=patch.yaml
4.3.3 kubectl label - 管理标签
bash
# 添加标签
kubectl label pods nginx environment=production
kubectl label pods nginx team=backend version=v1 --overwrite
# 删除标签(标签名后加 -)
kubectl label pods nginx team-
# 查看标签
kubectl get pods --show-labels
# 标签条件查询
kubectl get pods -l 'environment=production'
kubectl get pods -l 'environment!=development'
kubectl get pods -l 'version in (v1,v2,v3)'
# 跨命名空间设置标签
kubectl label pods nginx environment=production -n production
4.3.4 kubectl annotate - 管理注解
bash
# 添加注解
kubectl annotate pod nginx description="Production web server"
# 更新注解
kubectl annotate pod nginx description="Updated description" --overwrite
# 删除注解
kubectl annotate pod nginx description-
# 查看注解
kubectl get pod nginx -o jsonpath='{.metadata.annotations}'
4.4 集群管理命令
4.4.1 kubectl cluster-info - 集群信息
bash
# 查看集群基本信息
kubectl cluster-info
# 输出示例
Kubernetes control plane is running at https://api.example.com:6443
CoreDNS is running at https://api.example.com:6443/api/v1/namespaces/kube-system/services/kube-dns:dns
# 查看集群详细信息
kubectl cluster-info dump
# 查看所有组件状态
kubectl get componentstatuses
kubectl get cs
# 输出示例
NAME STATUS MESSAGE ERROR
scheduler Healthy ok
controller-manager Healthy ok
etcd-0 Healthy {"health":"true"}
# 查看 API 版本
kubectl api-versions
# 查看可用资源
kubectl api-resources
4.4.2 kubectl top - 资源监控
bash
# 查看节点资源使用
kubectl top node
kubectl top node worker-1
# 输出示例
NAME CPU(cores) CPU% MEMORY(bytes) MEMORY%
worker-1 450m 22% 2048Mi 45%
worker-2 320m 16% 1536Mi 34%
# 查看 Pod 资源使用
kubectl top pod
kubectl top pod --all-namespaces
# 按标签过滤
kubectl top pod -l app=nginx
# 查看特定 Pod
kubectl top pod nginx-pod
# 排除系统命名空间
kubectl top pod -A --exclude-resouce=kube-system
# 查看历史资源使用(需要 Metrics Server)
kubectl top pod --sort-by=memory
kubectl top pod --sort-by=cpu
4.4.3 kubectl cordon/uncordon - 节点调度控制
bash
# 标记节点为不可调度(cordon)
kubectl cordon worker-1
# 输出示例
node/worker-1 cordoned
# 查看节点状态
kubectl get nodes
# 输出示例
NAME STATUS ROLES AGE VERSION
worker-1 Ready,SchedulingDisabled <none> 30d v1.31.0
worker-2 Ready <none> 30d v1.31.0
# 恢复节点调度(uncordon)
kubectl uncordon worker-1
# 输出示例
node/worker-1 uncordoned
# 排除多个节点
kubectl cordon worker-1 worker-2
4.4.4 kubectl drain - 节点维护
bash
# 排空节点(安全驱逐 Pod)
kubectl drain worker-1
# 基础用法
kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data
# 参数说明
# --ignore-daemonsets: 忽略 DaemonSet Pod
# --delete-emptydir-data: 删除 EmptyDir 卷的 Pod
# --force: 强制删除非管理 Pod
# --grace-period: 优雅终止时间
# --timeout: 等待超时时间
# --skip-wait-for-delete-timeout: 跳过等待
# 完整示例
kubectl drain worker-1 \
--ignore-daemonsets \
--delete-emptydir-data \
--force \
--grace-period=60 \
--timeout=300s
# 排空后执行维护操作...
# ...
# 维护完成后恢复节点
kubectl uncordon worker-1
# 批量排空
for node in worker-1 worker-2 worker-3; do
kubectl drain $node --ignore-daemonsets --delete-emptydir-data --force
done
4.5 调试与排查命令
4.5.1 kubectl exec - 容器内执行命令
bash
# 进入容器(交互式 shell)
kubectl exec -it nginx-pod -- /bin/sh
kubectl exec -it nginx-pod -- bash
# 执行单个命令
kubectl exec nginx-pod -- ls /app
kubectl exec nginx-pod -- cat /app/config.yaml
# 多容器 Pod - 指定容器
kubectl exec -it nginx-pod -c nginx-container -- /bin/sh
# 执行特定用户
kubectl exec -it nginx-pod --user=appuser -- /bin/sh
# 工作目录
kubectl exec nginx-pod -w /app -- ls
# 查看环境变量
kubectl exec nginx-pod -- env
# 复制文件到容器
kubectl exec nginx-pod -- tar cf - /path/in/container | tar xf - -C /local/path
# 调试容器(使用 debug 镜像)
kubectl debug nginx-pod -it --image=busybox --share-processes --copy-to=debug-pod
4.5.2 kubectl port-forward - 端口转发
bash
# 转发本地端口到 Pod
kubectl port-forward pod/nginx-pod 8080:80
# 使用服务名转发
kubectl port-forward service/nginx-svc 8080:80
# 转发到所有地址(允许远程连接)
kubectl port-forward --address 0.0.0.0 pod/nginx-pod 8080:80
# 随机本地端口
kubectl port-forward pod/nginx-pod :80
# 转发多个端口
kubectl port-forward pod/nginx-pod 8080:80 8443:443
# 后台运行
kubectl port-forward pod/nginx-pod 8080:80 &
# 常用场景:连接数据库
kubectl port-forward svc/mysql-svc 3306:3306
# 然后使用 mysql -h localhost -P 3306 -u root -p 连接
# 常用场景:调试 Web 服务
kubectl port-forward deployment/nginx 8080:80
# 访问 http://localhost:8080
4.5.3 kubectl proxy - API 代理
bash
# 启动代理(默认端口 8001)
kubectl proxy
# 输出示例
Starting to serve on 127.0.0.1:8001
# 指定端口
kubectl proxy --port=8080
# 允许非本地连接
kubectl proxy --address=0.0.0.0 --port=8080
# 不打开 API 文档页面
kubectl proxy --www=/static/html --www-prefix=/static/
# 通过代理访问 API
curl http://localhost:8001/api/v1/namespaces/default/pods
# 访问特定服务
curl http://localhost:8001/api/v1/namespaces/default/services/my-service/proxy/
# 查看 Kubernetes Dashboard
curl http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/
4.5.4 kubectl cp - 文件复制
bash
# 从 Pod 复制文件到本地
kubectl cp default/nginx-pod:/app/logs/app.log ./app.log
# 从本地复制文件到 Pod
kubectl cp ./config.yaml default/nginx-pod:/app/config.yaml
# 多容器 Pod - 指定容器
kubectl cp ./file.txt default/nginx-pod:/app/file.txt -c nginx-container
# 复制整个目录
kubectl cp default/nginx-pod:/app/logs -c nginx-container ./logs
# 使用 tar 复制目录(保留权限)
kubectl exec nginx-pod -- tar cf - /app | tar xf - -C ./app
# 从命名空间复制
kubectl cp namespace/nginx-pod:/app/file.txt ./file.txt
# 复制多个文件
kubectl cp ./file1.txt ./file2.txt namespace/nginx-pod:/app/
4.6 配置管理命令
4.6.1 kubectl config - 配置管理
bash
# 查看当前配置
kubectl config view
# 查看当前上下文
kubectl config current-context
# 列出所有上下文
kubectl config get-contexts
# 切换上下文
kubectl config use-context production
# 设置命名空间
kubectl config set-context --current --namespace=my-namespace
# 重命名上下文
kubectl config rename-context old-name new-name
# 删除上下文
kubectl config delete-context dev
# 添加集群
kubectl config set-cluster prod \
--server=https://api.production.com:6443 \
--certificate-authority=/path/to/ca.crt
# 添加用户
kubectl config set-credentials admin \
--client-certificate=/path/to/cert.crt \
--client-key=/path/to/cert.key
# 创建上下文
kubectl config set-context prod-admin \
--cluster=prod \
--user=admin \
--namespace=production
# 设置默认编辑器
export KUBE_EDITOR="vim"
# 查看具体配置值
kubectl config view --minify
kubectl config view --raw
4.6.2 kubectl auth - 权限检查
bash
# 检查用户权限
kubectl auth can-i create pods
kubectl auth can-i create pods --as=developer
# 详细权限信息
kubectl auth can-i create pods --as=developer --list
# 检查特定资源权限
kubectl auth can-i get pods
kubectl auth can-i delete pods/nginx
# 检查命名空间权限
kubectl auth can-i list pods -n production
# 模拟用户操作
kubectl auth can-i '*' pods --as=system:serviceaccount:production:default
# 查看谁有权限执行某操作
kubectl auth whoami
# 输出示例
USERNAME GROUPS
default system:serviceaccounts
system:authenticated
五、高级用法
5.1 命令补全
Bash 补全
bash
# 生成补全脚本
kubectl completion bash
# 临时启用(当前会话)
source <(kubectl completion bash)
# 永久启用
echo "source <(kubectl completion bash)" >> ~/.bashrc
echo "source <(kubectl completion bash)" >> ~/.bash_profile
# 保存到系统目录
kubectl completion bash > /etc/bash_completion.d/kubectl
# macOS 使用 brew 安装的 bash-completion
brew install bash-completion
kubectl completion bash > $(brew --prefix)/etc/bash_completion.d/kubectl
Zsh 补全
bash
# 生成补全脚本
kubectl completion zsh
# 临时启用
source <(kubectl completion zsh)
# 永久启用
echo "source <(kubectl completion zsh)" >> ~/.zshrc
Fish 补全
bash
kubectl completion fish | source
# 或添加到配置
kubectl completion fish > ~/.config/fish/completions/kubectl.fish
5.2 别名设置
bash
# ~/.bashrc 或 ~/.zshrc 中添加
# kubectl 基础别名
alias k=kubectl
# get 命令别名
alias kg='kubectl get'
alias kgs='kubectl get services'
alias kgp='kubectl get pods'
alias kgd='kubectl get deployments'
alias kgn='kubectl get nodes'
alias kgns='kubectl get namespaces'
# describe 命令别名
alias kd='kubectl describe'
alias kdp='kubectl describe pod'
alias kdd='kubectl describe deployment'
# 常用操作
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'
alias kcf='kubectl create -f'
# 日志
alias klf='kubectl logs -f'
alias klp='kubectl logs -f pod'
# 执行
alias kex='kubectl exec -it'
# 命名空间
alias kswitch='kubectl config set-context --current --namespace'
# apply 常用组合
alias kak='kubectl apply -k' # Kustomize
alias kav='kubectl apply --validate=false -f'
alias kdd='kubectl diff -f'
# 状态查看
alias ktop='kubectl top'
alias kctx='kubectl config current-context'
alias kcon='kubectl config get-contexts'
# 快速进入命名空间
kns() { kubectl config set-context --current --namespace=$1 }
5.3 输出格式化
bash
# 默认表格输出
kubectl get pods
# JSON 输出
kubectl get pods -o json
# YAML 输出
kubectl get pods -o yaml
# 仅名称
kubectl get pods -o name
# 宽表输出(包含更多信息)
kubectl get pods -o wide
# 自定义列
kubectl get pods -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP
# 使用文件定义列
kubectl get pods -o=custom-columns-file=columns.txt
# JSONPath 提取
kubectl get pods nginx -o jsonpath='{.status.podIP}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}:{.status.podIP}{"\n"}{end}'
# Go 模板
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
# 格式化输出(处理多资源)
kubectl get all -o name
# 查看事件(按时间排序)
kubectl get events --sort-by='.lastTimestamp'
# 查看错误事件
kubectl get events --field-selector type=Warning
# 查看特定资源事件
kubectl get events --field-selector involvedObject.name=nginx-pod
5.4 资源配额管理
kubectl scale - 扩缩容
bash
# 扩容 Deployment
kubectl scale deployment nginx --replicas=5
# 缩容
kubectl scale deployment nginx --replicas=2
# 根据当前状态扩缩容
kubectl scale deployment nginx --current-replicas=3 --replicas=5
# 扩缩容多个资源
kubectl scale deployment nginx redis --replicas=3
# 扩缩容到 0(暂停)
kubectl scale deployment nginx --replicas=0
kubectl set - 资源配置
bash
# 更新容器镜像
kubectl set image deployment/nginx nginx=nginx:1.22
# 记录变更
kubectl set image deployment/nginx nginx=nginx:1.22 --record
# 查看更新历史
kubectl rollout history deployment/nginx
# 设置资源限制
kubectl set resources deployment nginx -c=nginx --limits=cpu=500m,memory=256Mi --requests=cpu=100m,memory=128Mi
# 设置环境变量(需要使用 Secrets/ConfigMap 引用)
kubectl set env deployment/nginx --from=secret/mysecret
# 设置服务账号
kubectl set serviceaccount deployment/nginx sa-name
# 取消镜像
kubectl unset image deployment/nginx
kubectl rollout - 部署管理
bash
# 查看部署状态
kubectl rollout status deployment/nginx
# 查看部署历史
kubectl rollout history deployment/nginx
# 回滚到上一版本
kubectl rollout undo deployment/nginx
# 回滚到指定版本
kubectl rollout undo deployment/nginx --to-revision=2
# 暂停部署(用于多次更新)
kubectl rollout pause deployment/nginx
# 恢复部署
kubectl rollout resume deployment/nginx
# 查看特定版本详情
kubectl rollout history deployment/nginx --revision=3
六、实战场景
6.1 常用操作组合
场景一:新应用部署完整流程
bash
# 1. 创建命名空间
kubectl create namespace myapp
# 2. 应用部署清单
kubectl apply -f ./myapp/ -n myapp
# 3. 检查 Pod 状态
kubectl get pods -n myapp -w
# 4. 查看 Deployment 状态
kubectl rollout status deployment myapp -n myapp
# 5. 暴露服务
kubectl expose deployment myapp --port=8080 --target-port=8080 --type=NodePort -n myapp
# 6. 查看服务
kubectl get svc -n myapp
# 7. 查看日志
kubectl logs -f deployment/myapp -n myapp
# 8. 测试服务
curl http://<node-ip>:<node-port>/health
场景二:日常巡检脚本
bash
#!/bin/bash
# kubernetes-daily-check.sh
NAMESPACE=${1:-default}
echo "======================================"
echo "Kubernetes Daily Check Report"
echo "Time: $(date)"
echo "Namespace: $NAMESPACE"
echo "======================================"
echo -e "\n[1] Cluster Status"
kubectl cluster-info
kubectl get nodes
echo -e "\n[2] Failed/Unhealthy Pods"
kubectl get pods -n $NAMESPACE --field-selector=status.phase!=Running
echo -e "\n[3] Pods with Restarts"
kubectl get pods -n $NAMESPACE --no-headers | awk '$4 > 5 {print}'
echo -e "\n[4] Resource Usage"
kubectl top nodes
kubectl top pods -n $NAMESPACE
echo -e "\n[5] Recent Events"
kubectl get events -n $NAMESPACE --sort-by='.lastTimestamp' | tail -20
echo -e "\n[6] Pending PVCs"
kubectl get pvc -n $NAMESPACE --field-selector=status.phase=Pending
echo -e "\n[7] Failed Jobs"
kubectl get jobs -n $NAMESPACE --field-selector=status.failed=true
echo -e "\n[8] HPA Status"
kubectl get hpa -n $NAMESPACE 2>/dev/null || echo "No HPA configured"
echo -e "\n======================================"
echo "Check Complete"
echo "======================================"
场景三:快速问题诊断
bash
#!/bin/bash
# diagnose.sh <pod-name> [namespace]
POD=$1
NAMESPACE=${2:-default}
echo "======================================"
echo "Diagnosing Pod: $POD"
echo "Namespace: $NAMESPACE"
echo "======================================"
echo -e "\n[1] Pod Basic Info"
kubectl get pod $POD -n $NAMESPACE -o wide
echo -e "\n[2] Pod Detailed Status"
kubectl describe pod $POD -n $NAMESPACE
echo -e "\n[3] Recent Events"
kubectl get events -n $NAMESPACE --field-selector involvedObject.name=$POD --sort-by='.lastTimestamp' | tail -10
echo -e "\n[4] Container Logs"
kubectl logs $POD -n $NAMESPACE --tail=50
echo -e "\n[5] Previous Container Logs (if restarted)"
kubectl logs $POD -n $NAMESPACE --previous --tail=50
echo -e "\n[6] Check Resource Quota"
kubectl describe resourcequota -n $NAMESPACE
echo -e "\n[7] Check LimitRange"
kubectl describe limitrange -n $NAMESPACE
echo -e "\n======================================"
6.2 故障排查流程
Pod 处于 Pending 状态
bash
# 1. 查看 Pod 详情
kubectl describe pod <pod-name>
# 2. 检查可能原因
# - 资源不足:kubectl describe node
# - 污点/容忍:kubectl describe node | grep -A 10 "Taints"
# - PVC 未绑定:kubectl get pvc
# - 调度失败:查看 Events
# 3. 解决方案
# 扩容节点
kubectl scale deployment <deploy> --replicas=3
# 或添加新节点
# 清理未使用的 PVC
kubectl delete pvc <unused-pvc>
Pod 处于 ImagePullBackOff
bash
# 1. 查看详情
kubectl describe pod <pod-name>
# 2. 检查镜像
# - 镜像名称错误
# - 镜像不存在
# - 认证失败
# 3. 解决方案
# 修正镜像名称
kubectl set image deployment/<name> <container>=correct-image:tag
# 创建 Secret(如果需要认证)
kubectl create secret docker-registry my-registry \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass \
--docker-email=user@example.com
# 更新 Pod Spec
kubectl patch deployment/<name> \
--type=json \
-p='[{"op":"add","path":"/spec/template/spec/imagePullSecrets","value":[{"name":"my-registry"}]}]'
Pod 处于 CrashLoopBackOff
bash
# 1. 查看日志
kubectl logs <pod-name> --previous
# 2. 检查应用配置
kubectl exec <pod-name> -- env
kubectl exec <pod-name> -- cat /app/config.yaml
# 3. 常见原因
# - 应用启动失败
# - 健康检查失败
# - 配置错误
# - 依赖服务不可达
# 4. 解决方案
# 修改启动命令
kubectl patch deployment <name> --type='strategic' -p '{
"spec": {
"template": {
"spec": {
"containers": [{
"name": "app",
"command": ["正确的命令"]
}]
}
}
}
}'
# 调整健康检查
kubectl patch deployment <name> --type='strategic' -p '{
"spec": {
"template": {
"spec": {
"containers": [{
"name": "app",
"readinessProbe": {"initialDelaySeconds": 30}
}]
}
}
}
}'
服务无法访问
bash
# 1. 检查 Service 存在
kubectl get svc <service-name>
# 2. 检查 Endpoints
kubectl get endpoints <service-name>
# 3. 检查 Pod 选择器匹配
kubectl get pods -l app=your-app
# 4. 检查 Pod 网络策略
kubectl get networkpolicy -n <namespace>
# 5. 测试连接
kubectl run test --image=busybox --rm -it -- sh
# 在容器内: wget -O- http://<service-ip>:port
# 6. 检查 DNS
kubectl run dns-test --image=busybox -- nslookup <service-name>
七、最佳实践与技巧
7.1 生产环境建议
1. 版本管理
bash
# 保持 kubectl 版本与集群版本兼容
# 建议:kubectl 版本与集群版本差异不超过 1 个小版本
# 检查版本
kubectl version --short
# 查看集群版本
kubectl version -o json | jq '.serverVersion.gitVersion'
2. 配置安全
bash
# 不要在 kubeconfig 中存储明文密码,使用证书或 Token
# 定期轮换证书
kubectl certificate approve <csr-name>
# 使用 RBAC 最小权限原则
kubectl auth can-i --list --as=serviceaccount:default:sa-name -n production
3. 资源管理
bash
# 设置资源限制和请求
kubectl set resources deployment app \
--limits=cpu=500m,memory=256Mi \
--requests=cpu=100m,memory=64Mi
# 使用 LimitRange 设置默认值
kubectl apply -f - <<EOF
apiVersion: v1
kind: LimitRange
metadata:
name: default-limits
namespace: production
spec:
limits:
- default:
cpu: 500m
memory: 256Mi
defaultRequest:
cpu: 100m
memory: 64Mi
type: Container
EOF
4. 日志管理
bash
# 应用级别日志聚合
kubectl logs -l app=myapp --all-containers=true -f | tee app.log
# 日志轮转配置(Pod Spec)
# 使用 stdout,由容器运行时处理轮转
# 集中式日志(ELK/Loki)
kubectl apply -f - <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
name: fluentd-config
namespace: kube-system
data:
fluent.conf: |
<source>
@type tail
@id input-tail-containers
path /var/log/containers/*.log
</source>
EOF
7.2 效率提升技巧
1. 快速切换上下文
bash
# 在 ~/.zshrc 或 ~/.bashrc 中添加
function kc() {
kubectl config use-context "$1"
}
# 列出并选择上下文
function kcs() {
kubectl config get-contexts | awk 'NR>1 {print NR-1, $1}' | fzf | awk '{print $2}' | xargs kubectl config use-context
}
2. 快速查看资源 YAML
bash
# 查看 Pod YAML(不含状态)
kubectl get pod nginx -o yaml --dry-run=client
# 查看完整 YAML
kubectl get pod nginx -o yaml
# 提取特定字段
kubectl get pod nginx -o jsonpath='{.spec.containers[0].image}'
3. 批量操作
bash
# 批量删除 Terminating 状态的命名空间
kubectl get ns | grep Terminating | awk '{print $1}' | xargs kubectl delete ns --force --grace-period=0
# 批量删除 Completed 状态的 Pod
kubectl get pods -A | grep Completed | awk '{print $1, $2}' | while read ns pod; do
kubectl delete pod $pod -n $ns
done
# 批量重启 Deployment
kubectl get deploy -o name | xargs kubectl rollout restart
4. 调试技巧
bash
# 使用 debug 镜像创建调试 Pod
kubectl debug nginx-pod -it --image=busybox --share-processes
# 复制 Pod 进行调试
kubectl debug nginx-pod --image=busybox --copy-to=debug-pod -- sh
# 查看资源使用趋势
kubectl top pod --sort-by=cpu -A | head -20
# 快速查看所有命名空间资源
kubectl get all -A -o wide | grep -v kube-system
八、常见问题与解决方案
问题 1:连接集群失败
症状:
plaintext
Unable to connect to the server: dial tcp: i/o timeout
排查步骤:
bash
# 1. 检查网络连通性
ping <api-server-url>
# 2. 检查 API Server 可达性
curl -k https://<api-server>/healthz
# 3. 检查 kubeconfig 配置
kubectl config view
# 4. 检查证书是否过期
openssl x509 -in /path/to/cert.crt -noout -dates
# 5. 检查 DNS 解析
nslookup <api-server-url>
解决方案:
bash
# 更新 kubeconfig
kubectl config view --raw > ~/.kube/config
# 设置正确的 API Server 地址
kubectl config set-cluster my-cluster --server=https://correct-api-server:6443
# 更新证书
kubectl config set-cluster my-cluster --certificate-authority=/path/to/new-ca.crt
问题 2:权限被拒绝
症状:
plaintext
Error from server (Forbidden): pods is forbidden: User "xxx" cannot list resource "pods" in API group "" in the namespace "default"
排查步骤:
bash
# 1. 检查当前用户权限
kubectl auth can-i --list
# 2. 模拟其他用户检查
kubectl auth can-i get pods --as=problematic-user
# 3. 查看 RBAC 配置
kubectl get role,rolebinding -n <namespace>
解决方案:
bash
# 创建 Role
kubectl create role pod-reader --verb=get,list,watch --resource=pods
# 创建 RoleBinding
kubectl create rolebinding pod-reader-binding \
--role=pod-reader \
--user=username \
--namespace=default
# 或使用 ClusterRoleBinding(集群级别)
kubectl create clusterrolebinding pod-reader-binding \
--clusterrole=pod-reader \
--user=username
问题 3:Pod 无法调度
症状:
plaintext
0/3 nodes are available: 1 Insufficient memory, 2 node(s) had taints that the pod didn't tolerate.
排查步骤:
bash
# 1. 查看节点状态
kubectl get nodes -o wide
# 2. 检查资源
kubectl describe node <node-name> | grep -A 5 "Allocated resources"
# 3. 检查污点
kubectl describe node <node-name> | grep Taints
# 4. 检查 Pod 容忍
kubectl get pod <pod-name> -o jsonpath='{.spec.tolerations}'
解决方案:
bash
# 添加容忍
kubectl patch pod <pod-name> -p '{
"spec": {
"tolerations": [
{"key": "node.kubernetes.io/not-ready", "operator": "Exists", "effect": "NoSchedule"}
]
}
}'
# 移除污点
kubectl taint nodes <node-name> dedicated-
# 增加节点
# 或清理现有资源
问题 4:镜像拉取失败
症状:
plaintext
ImagePullBackOff: Back-off pulling image "registry.example.com/image:tag"
排查步骤:
bash
# 1. 检查镜像是否存在
docker pull <image> # 在有权限的环境中
# 2. 检查 Secret
kubectl get secret -n <namespace>
# 3. 检查镜像名称
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].image}'
解决方案:
bash
# 创建镜像拉取 Secret
kubectl create secret docker-registry my-registry \
--docker-server=https://registry.example.com \
--docker-username=<user> \
--docker-password=<password>
# 挂载到 Pod
kubectl patch serviceaccount default -p '{"imagePullSecrets": [{"name": "my-registry"}]}'
# 或在 Pod Spec 中直接指定
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
imagePullSecrets:
- name: my-registry
containers:
- name: app
image: registry.example.com/image:tag
EOF
问题 5:无法删除资源
症状:
plaintext
Error from server (Conflict): ... Operation cannot be fulfilled
排查步骤:
bash
# 1. 检查 Finalizers
kubectl get pod <pod-name> -o jsonpath='{.metadata.finalizers}'
# 2. 检查资源状态
kubectl describe <resource-type> <name>
# 3. 检查是否有守护进程占用
kubectl get events --field-selector involvedObject.name=<name>
解决方案:
bash
# 移除 Finalizers(强制删除)
kubectl patch <resource-type> <name> -p '{"metadata":{"finalizers":null}}' --type=merge
# 清理 Terminating 状态的命名空间
kubectl get namespace <ns> -o json | \
jq '.spec.finalizers = []' | \
kubectl replace --raw "/api/v1/namespaces/<ns>/finalize" -f -
# 强制删除 Pod
kubectl delete pod <pod> --grace-period=0 --force
问题 6:内存/资源耗尽
症状:
plaintext
kubectl: error: Insufficient memory
# 或操作超时
排查步骤:
bash
# 1. 检查节点资源
kubectl top nodes
# 2. 查看资源配额
kubectl describe resourcequota
# 3. 查看 LimitRange
kubectl describe limitrange
解决方案:
bash
# 清理不必要的资源
kubectl delete pod <unused-pod>
# 增加资源配额
kubectl patch resourcequota <quota-name> -p '{
"spec": {
"hard": {
"requests.memory": "16Gi"
}
}
}'
# 调整现有 Pod 资源
kubectl edit deployment <name>
九、附录
常用资源缩写表
| 全称 | 缩写 | 说明 |
|---|---|---|
| pods | po | Pod |
| services | svc | 服务 |
| deployments | deploy | 部署 |
| replicasets | rs | 副本集 |
| statefulsets | sts | 有状态副本集 |
| daemonsets | ds | 守护进程集 |
| configmaps | cm | 配置映射 |
| namespaces | ns | 命名空间 |
| nodes | no | 节点 |
| persistentvolumes | pv | 持久卷 |
| persistentvolumeclaims | pvc | 持久卷声明 |
| ingresses | ing | 入口 |
| cronjobs | cj | 定时任务 |
| jobs | - | 任务 |
| endpoints | ep | 端点 |
| events | ev | 事件 |
| serviceaccounts | sa | 服务账号 |
| clusterroles | - | 集群角色 |
| clusterrolebindings | - | 集群角色绑定 |
kubectl 常用快捷键
bash
# ~/.kubectl_aliases 或 ~/.bashrc 中定义
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias ka='kubectl apply'
alias kdel='kubectl delete'
alias kex='kubectl exec -it'
alias klf='kubectl logs -f'
alias kpf='kubectl port-forward'
参考链接
结语
kubectl 是 Kubernetes 管理的核心工具,掌握好 kubectl 的使用可以让你的 Kubernetes 管理工作事半功倍。本文从安装配置到高级用法,从日常操作到故障排查,较为全面地介绍了 kubectl 的使用方法。
建议在实际工作中多加练习,熟练运用各种命令和技巧。同时,养成良好的习惯,如使用 kubeconfig 管理多集群、配置命令补全、使用 YAML 文件管理资源等,这些都将帮助你更高效地管理 Kubernetes 集群。
如有任何问题或建议,欢迎交流讨论。