入门
kubectl 基础
kubectl 是 Kubernetes 的命令行工具。get 列出资源,create 创建新资源,expose 创建 Service,scale 修改副本数。describe 提供资源的详细信息。
# cluster info
kubectl cluster-info
# list nodes
kubectl get nodes
# list pods (all namespaces)
kubectl get pods --all-namespaces
# create a deployment
kubectl create deployment nginx --image=nginx
# expose deployment as service
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# scale deployment
kubectl scale deployment nginx --replicas=3
# get detailed info
kubectl describe pod <pod-name>
# view logs
kubectl logs <pod-name>输出格式化
-o 标志控制输出。yaml/json 显示完整资源规格;jsonpath 和 custom-columns 提取特定字段用于脚本;-w 实时监视变化。脚本中使用 --no-headers 可去掉列名。
# wide format (more columns)
kubectl get pods -o wide
# YAML output
kubectl get pod nginx -o yaml
# JSON output
kubectl get pod nginx -o json
# jsonpath (extract specific fields)
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
# show labels
kubectl get pods --show-labels
# watch for changes
kubectl get pods -w上下文与配置
一个上下文捆绑了集群地址、用户凭证和命名空间。kubeconfig 文件(默认 ~/.kube/config)存储这些信息。可通过 KUBECONFIG 环境变量组合多个文件来管理多个集群。
# view current config
kubectl config view
# list contexts
kubectl config get-contexts
# switch context
kubectl config use-context my-cluster
# set default namespace for current context
kubectl config set-context --current --namespace=dev
# show current context
kubectl config current-context
# KUBECONFIG with multiple files
export KUBECONFIG=~/.kube/config:~/.kube/prod-configexplain 与 API 资源
api-resources 列出集群支持的资源;explain 显示任意资源的 OpenAPI 模式——在终端内编写 YAML 时非常实用。使用 --recursive 可转储完整的嵌套结构。
# list all resource types
kubectl api-resources
# list namespaced vs cluster-scoped
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
# explain a resource's fields
kubectl explain pod
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy
# explain with recursion (all nested fields)
kubectl explain pod --recursive
# include description
kubectl explain pod.spec.containers.resources --api-version=apps/v1Dry Run 与生成 YAML
--dry-run=client -o yaml 是从命令式命令生成清单的标准方法。--dry-run=server 会与真实 apiserver 校验(准入 webhook、模式)但不持久化。非常适合引导声明式 YAML。
# generate YAML without applying
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml
# pipe generated YAML straight to a file
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml
# apply the generated manifest
kubectl apply -f nginx.yaml
# dry-run against the server (validates with apiserver)
kubectl apply -f nginx.yaml --dry-run=server
# generate a service from a deployment
kubectl create service clusterip my-svc --tcp=80:80 --dry-run=client -o yaml帮助与自动补全
每个 kubectl 命令都支持 --help 并附示例。Shell 补全能极大减少输入并暴露子命令。alias k=kubectl 在从业者中近乎通用——配合补全使用体验最佳。
# top-level help
kubectl --help
# subcommand help
kubectl create --help
kubectl explain --help
# generate bash completion
kubectl completion bash > /etc/bash_completion.d/kubectl
# zsh completion
source <(kubectl completion zsh)
# alias k=kubectl with completion
alias k=kubectl
complete -o default -F __start_kubectl k
# shorthand: kubectl -> k
echo 'alias k=kubectl' >> ~/.bashrcPod
Pod 清单
Pod 是最小可部署单元,持有一个或多个共享网络和存储的容器。同一 Pod 内的容器总是共同调度到同一节点。很少直接创建 Pod——应使用 Deployment 或 Job。
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
restartPolicy: Always多容器 Pod(Sidecar)
多容器 Pod 共享网络(相同 IP、端口空间)和卷。常见模式:sidecar(辅助)、adapter(转换输出)、ambassador(代理)。共享的 emptyDir 卷让 sidecar 读取主容器写入的日志。
apiVersion: v1
kind: Pod
metadata:
name: web-with-logs
spec:
containers:
- name: app
image: nginx
volumeMounts:
- name: shared-logs
mountPath: /var/log/nginx
- name: log-shipper
image: busybox
command: ["sh", "-c", "tail -f /var/log/nginx/access.log"]
volumeMounts:
- name: shared-logs
mountPath: /var/log/nginx
readOnly: true
volumes:
- name: shared-logs
emptyDir: {}Pod 生命周期与阶段
Pod 的 phase 是高层级状态(Pending、Running、Succeeded、Failed)。容器状态(Waiting/Running/Terminated)给出真正细节—— 例如 CrashLoopBackOff 表示容器反复退出。检查重启次数和事件来诊断。
# pod phases: Pending | Running | Succeeded | Failed | Unknown
kubectl get pod nginx
# show status including container states
kubectl get pod nginx -o jsonpath='{.status}'
# container states: Waiting | Running | Terminated
kubectl describe pod nginx
# common Waiting reasons: ImagePullBackOff, CrashLoopBackOff, CreateContainerConfigError
kubectl get pods --field-selector=status.phase=Pending
# restart count reveals crash loops
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[*].restartCount}'Pod 状态与事件
事件是集群对资源的审计日志——调度、拉取、拉取错误、存活探针失败。它们会过期(默认约 1 小时),所以调试时要及时捕获。describe 将事件与资源规格打包,便于快速分诊。
# full describe (includes Events at the bottom)
kubectl describe pod nginx
# list cluster events sorted by time
kubectl get events --sort-by=.lastTimestamp
# events for a specific namespace
kubectl get events -n default
# watch events live
kubectl get events -w
# filter events by type
kubectl get events --field-selector type=Warning
# events for a specific pod
kubectl get events --field-selector involvedObject.name=nginxexec 与端口转发
exec 在容器内运行命令;-it 为 shell 分配 TTY。port-forward 将本地端口隧道到 Pod/Service 而不对外暴露——从笔记本调试数据库或 Web UI 的必备手段。