跳到主要内容

Kubernetes 速查表

本页面汇总了 Kubernetes 最常用的命令和资源定义,作为快速参考。

kubectl 常用技巧

自动补全

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

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

# Fish
kubectl completion fish | source

# PowerShell
kubectl completion powershell | Out-String | Invoke-Expression

常用别名

# kubectl 别名
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias ka='kubectl apply'
alias kl='kubectl logs'
alias kex='kubectl exec'

# 常用命令别名
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deploy'
alias kdp='kubectl describe pod'
alias klf='kubectl logs -f'
alias kaf='kubectl apply -f'

格式化输出

# YAML 格式
kubectl get pod my-pod -o yaml

# JSON 格式
kubectl get pod my-pod -o json

# 宽格式(显示更多信息)
kubectl get pods -o wide

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

# JSONPath 查询
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'

# 仅名称
kubectl get pods -o name

# 导出不含状态信息
kubectl get pod my-pod -o yaml --export

快速生成资源

# 生成 Pod YAML(不创建)
kubectl run my-pod --image=nginx --dry-run=client -o yaml

# 生成 Deployment YAML
kubectl create deployment my-app --image=nginx --replicas=3 --dry-run=client -o yaml

# 生成 Service YAML
kubectl expose deployment my-app --port=80 --target-port=8080 --dry-run=client -o yaml

# 从文件生成 ConfigMap YAML
kubectl create configmap my-config --from-file=config.yaml --dry-run=client -o yaml

调试和故障排查

# 查看资源事件
kubectl describe pod my-pod

# 查看 Pod 日志
kubectl logs my-pod
kubectl logs my-pod -c container-name # 多容器 Pod
kubectl logs my-pod --previous # 查看上一个容器的日志
kubectl logs my-pod -f # 实时跟踪日志
kubectl logs my-pod --tail=100 # 最后 100 行
kubectl logs my-pod --since=1h # 最近 1 小时的日志

# 进入容器执行命令
kubectl exec -it my-pod -- /bin/sh
kubectl exec -it my-pod -c container-name -- /bin/sh

# 端口转发
kubectl port-forward pod/my-pod 8080:80
kubectl port-forward svc/my-service 8080:80
kubectl port-forward deployment/my-deploy 8080:80

# 复制文件
kubectl cp my-pod:/path/to/file ./local-file
kubectl cp ./local-file my-pod:/path/to/file

# 使用调试容器
kubectl debug -it my-pod --image=busybox
kubectl debug -it my-pod --image=nicolaka/netshoot # 网络调试工具

常用命令

集群管理

# 查看集群信息
kubectl cluster-info

# 查看节点
kubectl get nodes
kubectl get nodes -o wide

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

# 查看组件状态
kubectl get componentstatuses

# 查看 API 资源
kubectl api-resources

# 查看 API 版本
kubectl api-versions

# 查看集群配置
kubectl config view
kubectl config current-context
kubectl config use-context <context-name>

Pod 管理

# 创建 Pod
kubectl apply -f pod.yaml

# 查看 Pod
kubectl get pods
kubectl get pods -o wide
kubectl get pods -n <namespace>

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

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

# 进入 Pod
kubectl exec -it <pod-name> -- /bin/sh

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

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

Deployment 管理

# 创建 Deployment
kubectl apply -f deployment.yaml
kubectl create deployment nginx --image=nginx

# 查看 Deployment
kubectl get deployments
kubectl describe deployment <name>

# 扩缩容
kubectl scale deployment <name> --replicas=5

# 更新
kubectl set image deployment/<name> <container>=<image>
kubectl rollout status deployment/<name>

# 回滚
kubectl rollout undo deployment/<name>
kubectl rollout undo deployment/<name> --to-revision=2

# 查看历史
kubectl rollout history deployment/<name>

StatefulSet 管理

# 创建 StatefulSet
kubectl apply -f statefulset.yaml

# 查看 StatefulSet
kubectl get statefulset
kubectl describe statefulset <name>

# 扩缩容
kubectl scale statefulset <name> --replicas=5

# 更新镜像
kubectl set image statefulset/<name> <container>=<image>

# 查看更新状态
kubectl rollout status statefulset/<name>

# 删除 StatefulSet
kubectl delete statefulset <name>

DaemonSet 管理

# 创建 DaemonSet
kubectl apply -f daemonset.yaml

# 查看 DaemonSet
kubectl get daemonset -A
kubectl describe daemonset <name> -n <namespace>

# 更新镜像
kubectl set image daemonset/<name> <container>=<image> -n <namespace>

# 查看更新状态
kubectl rollout status daemonset/<name> -n <namespace>

# 回滚
kubectl rollout undo daemonset/<name> -n <namespace>

Job 管理

# 创建 Job
kubectl apply -f job.yaml
kubectl create job my-job --image=busybox -- echo "Hello"

# 查看 Job
kubectl get jobs
kubectl describe job <name>

# 查看 Job 日志
kubectl logs job/<name>

# 删除 Job
kubectl delete job <name>

# 查看 Job 创建的 Pod
kubectl get pods -l job-name=<job-name>

CronJob 管理

# 创建 CronJob
kubectl apply -f cronjob.yaml
kubectl create cronjob my-cronjob --image=busybox --schedule="*/1 * * * *" -- echo "Hello"

# 查看 CronJob
kubectl get cronjobs
kubectl describe cronjob <name>

# 暂停 CronJob
kubectl patch cronjob <name> -p '{"spec":{"suspend":true}}'

# 恢复 CronJob
kubectl patch cronjob <name> -p '{"spec":{"suspend":false}}'

# 手动触发 CronJob(创建一次性 Job)
kubectl create job --from=cronjob/<cronjob-name> manual-job

# 删除 CronJob
kubectl delete cronjob <name>

Service 管理

# 创建 Service
kubectl expose deployment <name> --port=80 --type=NodePort
kubectl apply -f service.yaml

# 查看 Service
kubectl get svc
kubectl describe svc <name>

# 删除 Service
kubectl delete svc <name>

Ingress 管理

# 查看 Ingress
kubectl get ingress
kubectl describe ingress <name>

# 创建 Ingress
kubectl apply -f ingress.yaml

Gateway API 管理

# 查看 GatewayClass
kubectl get gatewayclass

# 查看 Gateway
kubectl get gateway -A
kubectl describe gateway <name> -n <namespace>

# 查看 HTTPRoute
kubectl get httproute -A
kubectl describe httproute <name> -n <namespace>

# 查看所有路由资源
kubectl get httproute,tcproute,grpcroute -A

# 从 Ingress 转换到 Gateway API
ingress2gateway print --all-namespaces

ConfigMap 和 Secret

# 创建 ConfigMap
kubectl create configmap <name> --from-literal=key=value
kubectl create configmap <name> --from-file=<file>

# 创建 Secret
kubectl create secret generic <name> --from-literal=key=value
kubectl create secret tls <name> --cert=<cert> --key=<key>

# 查看
kubectl get configmap
kubectl get secret

# 描述
kubectl describe configmap <name>
kubectl describe secret <name>

PV 和 PVC

# 查看
kubectl get pv
kubectl get pvc

# 描述
kubectl describe pv <name>
kubectl describe pvc <name>

RBAC

# 查看角色
kubectl get roles -n <namespace>
kubectl get clusterroles

# 查看角色绑定
kubectl get rolebindings -n <namespace>
kubectl get clusterrolebindings

# 检查权限
kubectl auth can-i <verb> <resource> --as=<user>

调试命令

# 查看资源事件
kubectl get events
kubectl get events --sort-by='.lastTimestamp'

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

# 资源使用情况
kubectl top nodes
kubectl top pods -n <namespace>

# JSONPath 查询
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'

kubectl 技巧

# 快速生成 YAML
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml

# 标签选择器
kubectl get pods -l app=nginx
kubectl get pods -l 'app in (nginx, redis)'

# 字段选择器
kubectl get pods --field-selector=status.phase=Running

# 格式化输出
kubectl get pods -o wide
kubectl get pods -o yaml
kubectl get pods -o json

# 别名
alias k='kubectl'
alias kgp='kubectl get pods'
alias kdp='kubectl describe pod'
alias klf='kubectl logs -f'

资源清单示例

Pod

apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: app
image: nginx
ports:
- containerPort: 80

Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: app
image: nginx
ports:
- containerPort: 80

Service

apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- port: 80
targetPort: 80
type: ClusterIP

Ingress

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80

Gateway API

# GatewayClass - 由基础设施提供商定义
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: my-gateway-class
spec:
controllerName: example.com/gateway-controller
---
# Gateway - 由集群管理员定义
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: my-gateway
spec:
gatewayClassName: my-gateway-class
listeners:
- name: http
protocol: HTTP
port: 80
---
# HTTPRoute - 由应用开发者定义
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: my-route
spec:
parentRefs:
- name: my-gateway
hostnames:
- "example.com"
rules:
- backendRefs:
- name: my-service
port: 80

ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
data:
key1: value1
key2: value2

Secret

apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
stringData:
key: value

PVC

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi

NetworkPolicy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress

StatefulSet

apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: nginx-headless
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi

DaemonSet

apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluentd
namespace: kube-system
spec:
selector:
matchLabels:
name: fluentd
template:
metadata:
labels:
name: fluentd
spec:
containers:
- name: fluentd
image: fluentd:v1.14
volumeMounts:
- name: varlog
mountPath: /var/log
volumes:
- name: varlog
hostPath:
path: /var/log

Job

apiVersion: batch/v1
kind: Job
metadata:
name: pi
spec:
template:
spec:
containers:
- name: pi
image: perl:5.34
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
restartPolicy: Never
backoffLimit: 4

CronJob

apiVersion: batch/v1
kind: CronJob
metadata:
name: hello
spec:
schedule: "* * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox:1.36
command: ["echo", "Hello"]
restartPolicy: OnFailure

常用标签和注解

常用标签

metadata:
labels:
app: my-app # 应用名称
tier: frontend # 层级
environment: prod # 环境
version: v1.0.0 # 版本

常用注解

metadata:
annotations:
kubernetes.io/description: "描述"
kubernetes.io/limit-ranger: "LimitRanger 配置"

资源缩写

资源类型缩写
podspo
servicessvc
deploymentsdeploy
replicasetsrs
statefulsetssts
daemonsetsds
jobsjob
cronjobscj
configmapscm
secretssecret
persistentvolumespv
persistentvolumeclaimspvc
namespacesns
nodesno
ingressesing
networkpoliciesnetpol

网络端口

组件端口
API Server6443
etcd2379-2380
Kubelet10250
NodePort30000-32767
kube-proxy10256

常用工具

kubectl 插件

# 安装 krew
curl -fsSL https://krew.sigs.k8s.io/install.sh | bash

# 安装插件
kubectl krew install view-utilization
kubectl krew install topology

图形化工具

  • Lens - Kubernetes IDE
  • Octant - 可视化工具
  • Kubernetes Dashboard - Web UI
  • k9s - 终端 UI

故障排查清单

Pod 问题

# 1. 检查 Pod 状态
kubectl get pods -n <ns>

# 2. 查看事件
kubectl describe pod <pod>

# 3. 查看日志
kubectl logs <pod>

# 4. 检查资源
kubectl top pod <pod>

# 5. 进入调试
kubectl exec -it <pod> -- /bin/sh

Service 问题

# 1. 检查 Service
kubectl get svc

# 2. 检查 Endpoint
kubectl get endpoints <service>

# 3. 检查 DNS
kubectl exec -it busybox -- nslookup <service>

# 4. 测试连接
kubectl run test --image=busybox --rm -it --restart=Never -- wget -qO- <service>

网络问题

# 1. 检查网络策略
kubectl get networkpolicy

# 2. 检查 iptables 规则
kubectl exec -it <node> -- iptables -L -n

# 3. 检查 kube-proxy
kubectl logs -n kube-system -l k8s-app=kube-proxy

常用快捷命令

# 快速部署
kubectl apply -f .

# 查看所有命名空间
kubectl get pods -A

# 实时监控
watch -n 1 kubectl get pods

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

# 导出资源
kubectl get deployment nginx -o yaml > nginx.yaml

学习资源

祝学习愉快!