入门
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 的必备手段。
# open an interactive shell
kubectl exec -it nginx -- sh
# run a one-off command
kubectl exec nginx -- ls /etc/nginx
# specify container in a multi-container pod
kubectl exec -it web-with-logs -c log-shipper -- sh
# forward a local port to a pod port
kubectl port-forward pod/nginx 8080:80
# forward to a service / deployment
kubectl port-forward svc/nginx 8080:80
kubectl port-forward deployment/nginx 8080:80
# forward to a random local port
kubectl port-forward pod/nginx :80删除与强制删除
删除受 Deployment/StatefulSet 管理的 Pod 会立即触发重建。--force --grace-period=0 跳过 TERM 信号宽限期,可能留下残留资源——谨慎使用。 卡在 Terminating 的 Pod 通常需要移除 finalizer。
# delete a pod (controller will recreate it)
kubectl delete pod nginx
# force delete immediately (bypasses graceful shutdown)
kubectl delete pod nginx --grace-period=0 --force
# delete by label
kubectl delete pods -l app=nginx
# delete all pods in a namespace
kubectl delete pods --all -n default
# delete a pod and wait for it to be gone
kubectl delete pod nginx --wait
# delete with a timeout
kubectl delete pod nginx --timeout=30sDeployment
Deployment 清单
Deployment 管理 ReplicaSet,并提供声明式滚动更新和回滚。spec.selector 必须匹配 spec.template.metadata.labels。template 定义要推出的 Pod 规格。
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80滚动更新策略
RollingUpdate(默认)逐步替换 Pod 实现零停机。maxSurge/maxUnavailable 控制推出速度和可用性。Recreate 在创建新 Pod 前先杀掉所有旧 Pod——用于应用不能同时运行两个版本时(如单卷写入者)。
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 10
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25% # extra pods above replicas during update
maxUnavailable: 25% # pods allowed down during update
# alternative: recreate (kills all, then starts new)
# strategy:
# type: Recreate
selector:
matchLabels:
app: nginx
template:回滚
每次对 Pod 模板的修改创建一个 ReplicaSet 版本。undo 将流量切回之前的 ReplicaSet。pause 让你在金丝雀增量之间做多次修复。用 --record(已弃用)或注解跟踪变更原因。
# view rollout history
kubectl rollout history deployment/nginx
# see details of a specific revision
kubectl rollout history deployment/nginx --revision=2
# undo to the previous revision
kubectl rollout undo deployment/nginx
# undo to a specific revision
kubectl rollout undo deployment/nginx --to-revision=2
# pause/resume a rollout (for canary pauses)
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx
# check rollout status
kubectl rollout status deployment/nginx扩缩容与 HPA
HPA 基于 CPU/内存或自定义指标扩缩副本数。CPU/内存需要 metrics-server。minReplicas 和 maxReplicas 限定扩缩范围。v2 API 支持多指标和 behavior(缩容 稳定化)。
# scale manually
kubectl scale deployment/nginx --replicas=5
# horizontal pod autoscaler (CPU target)
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
# list HPA
kubectl get hpa
# HPA manifest (v2 with custom metrics)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: nginx
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80更新镜像与重启
set image 触发新的 ReplicaSet 和滚动更新。rollout restart 是拉取最新镜像或刷新配置的最干净方式——它以相同规格创建新 ReplicaSet。edit 打开 $EDITOR 做临时修复。
# update container image
kubectl set image deployment/nginx nginx=nginx:1.26
# update from a specific container
kubectl set image deployment/nginx container=nginx:1.26 --record
# trigger a rollout restart (same image, recreate pods)
kubectl rollout restart deployment/nginx
# edit a deployment in editor
kubectl edit deployment/nginx
# patch a single field
kubectl patch deployment/nginx -p '{"spec":{"replicas":5}}'
# apply a manifest change
kubectl apply -f nginx-deployment.yamlDeployment 状态
Deployment 拥有 ReplicaSet;只有一个处于活跃状态(replicas>0)。旧 ReplicaSet 缩到 0 以备回滚。pod-template-hash 标签为每个 Pod 标记版本。检查 status.conditions 看 Available、Progressing、ReplicaFailure 信号。
# deployment status
kubectl get deployment nginx
# watch rollout
kubectl rollout status deployment/nginx
# show ReplicaSets owned by the deployment
kubectl get rs -l app=nginx
# show pods across all revisions
kubectl get pods -l app=nginx --show-labels
# pod-template-hash label distinguishes revisions
# kubectl get pods -l app=nginx,pod-template-hash=xxxx
# conditions: Available, Progressing, ReplicaFailure
kubectl get deployment nginx -o jsonpath='{.status.conditions}'Service
Service 类型
Service 提供稳定的 IP/DNS,在一组 Pod 间负载均衡。ClusterIP 是默认(仅集群内)。NodePort 和 LoadBalancer 对外暴露。ExternalName 是 DNS 别名,非代理。
# four service types:
# - ClusterIP (default): reachable inside the cluster
# - NodePort: exposed on each node's IP at a static port
# - LoadBalancer: cloud-provisioned external LB
# - ExternalName: DNS CNAME to an external host
# quick create
kubectl expose deployment nginx --port=80 --type=ClusterIP
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# external name (no proxying, pure DNS)
kubectl create service externalname my-svc --external-name=db.example.comClusterIP Service
ClusterIP 在集群内提供稳定的虚拟 IP 和 DNS 名。selector 匹配 Pod 标签;kube-proxy 编程 iptables/IPVS 在端点间负载均衡。通过 <svc>.<ns>.svc.cluster.local 或直接 <svc> 解析。
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: ClusterIP
selector:
app: nginx
ports:
- name: http
port: 80 # service port
targetPort: 80 # container port
protocol: TCP
# DNS: nginx.default.svc.cluster.local
# short names also work: nginx, nginx.default
# kube-dns / CoreDNS resolves the service VIPNodePort Service
NodePort 在每个节点上开放相同的静态端口(30000-32767)。访问任意 node:nodePort 的流量都会到达某个 Pod(kube-proxy 可能重定向到其他节点上的 Pod)。在无法配置云 LB 时有用;配合外部 LB 实现 HA。
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: NodePort
selector:
app: nginx
ports:
- port: 80
targetPort: 80
nodePort: 30080 # optional, 30000-32767 range
# reachable at <any-node-ip>:30080
# also still reachable via clusterIP:80
# get assigned nodePort
kubectl get svc nginx -o jsonpath='{.spec.ports[*].nodePort}'LoadBalancer Service
LoadBalancer 请求云提供商配置指向节点的外部负载均衡器。externalTrafficPolicy: Local 保留客户端源 IP(无 SNAT)但跳过跨节点负载均衡。就绪后 STATUS 显示分配的外部 IP。
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: LoadBalancer
selector:
app: nginx
ports:
- port: 80
targetPort: 80
# cloud-specific annotations
# annotations:
# service.beta.kubernetes.io/aws-load-balancer-type: nlb
# service.beta.kubernetes.io/azure-load-balancer-internal: "true"
# externalTrafficPolicy: Local preserves client IP
externalTrafficPolicy: Local
# status.ingress shows the external IP/hostnameHeadless Service
Headless Service(clusterIP: None)没有 VIP——DNS 直接返回 Pod IP。StatefulSet 必需它,以便每个 Pod 拥有稳定 DNS 名(pod-0.svc、pod-1.svc)。也用于想自行发现所有后端的客户端。
apiVersion: v1
kind: Service
metadata:
name: nginx-headless
spec:
clusterIP: None # makes it headless
selector:
app: nginx
ports:
- port: 80
targetPort: 80
# DNS returns pod IPs directly (not a VIP)
# A records: nginx-headless.default.svc.cluster.local
# -> 10.1.0.5, 10.1.0.6, 10.1.0.7
# used by StatefulSet for stable pod DNS:
# <pod-name>.<svc-name>.default.svc.cluster.localEndpoints 与 EndpointSlices
Endpoints/EndpointSlices 列出真正接收流量 的 Pod IP——只有 Ready 的 Pod 才会出现。如果 Service 没有端点,说明 Pod 未匹配 selector 或未 Ready。EndpointSlices(v1)对大型 Service 扩展性更好,是默认选择。
# view endpoints backing a service
kubectl get endpoints nginx
# endpoint slices (newer, more scalable)
kubectl get endpointslices -l kubernetes.io/service-name=nginx
# endpoints track pods that match the selector
# AND pass readiness checks
kubectl describe endpoints nginx
# a service with no ready pods has no endpoints
# - check pod readiness if traffic is refused
# - EndpointSlices are grouped by address type (IPv4/IPv6)
# manually managed endpoints (selector-less service)ConfigMap
创建 ConfigMap
ConfigMap 以键值对存储非敏感配置。--from-literal 用于内联值,--from-file 嵌入整个文件(文件名成为 key)。用于将配置与镜像解耦而无需重新构建。
# from literal values
kubectl create configmap app-config \
--from-literal=LOG_LEVEL=debug \
--from-literal=ENABLE_FEATURE=true
# from a file (key = filename, value = contents)
kubectl create configmap app-config --from-file=app.properties
# from a directory (one key per file)
kubectl create configmap app-config --from-file=configs/
# from an env file
kubectl create configmap app-config --from-env-file=app.env
# from a file with a custom key
kubectl create configmap app-config --from-file=custom-key=app.propertiesConfigMap 清单
data 存储字符串值(每个 key 在挂载时成为环境变量或文件)。多行字符串使用 YAML 块标量(|)。binaryData 接受 base64 二进制数据。每个 ConfigMap 总大小限制为 1 MiB。
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
LOG_LEVEL: "debug"
ENABLE_FEATURE: "true"
application.yml: |
server:
port: 8080
logging:
level: debug
binaryData:
# base64-encoded binary values
logo.png: iVBORw0KGgoAAAANSUhEUg...作为环境变量消费
envFrom 一次性注入 ConfigMap 的所有 key 为环境变量。env 配 configMapKeyRef 挑选单个 key。optional: true 让 Pod 在 ConfigMap 不存在时也能启动。ConfigMap 更新不会刷新运行中 Pod 的环境变量。
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: app-config
key: LOG_LEVEL
envFrom:
- configMapRef:
name: app-config # injects all keys as env vars
optional: true # pod starts even if CM missing作为卷消费
将 ConfigMap 作为卷挂载会把每个 key 投射为文件。ConfigMap 更新最终会反映到挂载文件中(由 kubelet 同步周期决定)——但应用必须重新读取。subPath 挂载固定单个 key 且不会更新。
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: config
mountPath: /etc/config
readOnly: true
volumes:
- name: config
configMap:
name: app-config
items: # optional: pick subset
- key: application.yml
path: app.yml # rename file
defaultMode: 0644
# each ConfigMap key becomes a file under /etc/config更新与重载
挂载的 ConfigMap 文件会自动刷新(kubelet 同步后),但环境变量在 Pod 生命周期内不可变——需重启 Pod 才能获取环境变量变更。rollout restart 是向 Deployment 传播配置更新的最干净方式。
# edit the configmap
kubectl edit configmap app-config
# patch a single key
kubectl patch configmap app-config \
--type merge -p '{"data":{"LOG_LEVEL":"info"}}'
# mounted files update within ~kubelet sync period (default 60s)
# but env vars do NOT update in running pods
# force pods to pick up new config by rolling them
kubectl rollout restart deployment/app
# verify the new value on a pod
kubectl exec app -- printenv LOG_LEVEL不可变 ConfigMap
设置 immutable: true 冻结 ConfigMap——任何修改都需要删除 + 重建。这极大减少了大型稳定配置的 kubelet-apiserver watch 流量(规模化时的重大可扩展性收益)。生产中常用于与镜像版本绑定的应用配置。
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
immutable: true
data:
LOG_LEVEL: "debug"
# once immutable, the only change allowed is delete + recreate
# benefits: kubelet does not watch it, lower apiserver load
# useful for large, stable configs in production
# make it mutable again
kubectl patch configmap app-config -p '{"immutable":false}'
# (this fails if currently immutable — must delete instead)Secret
创建 Secret
Secret 以 base64 编码存储敏感数据(默认未加密静止存储——生产环境应启用 encryption at rest)。generic/Opaque 用于任意数据,docker-registry 用于镜像拉取,tls 用于 Ingress TLS。切勿将 Secret YAML 提交到 git。
# generic (opaque) from literals
kubectl create secret generic db-creds \
--from-literal=username=admin \
--from-literal=password='S3cur3!'
# from a file (e.g. SSH key, certificate)
kubectl create secret generic ssh-key --from-file=ssh-privatekey=~/.ssh/id_rsa
# docker registry secret (for private image registries)
kubectl create secret docker-registry regcred \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass \
[email protected]
# TLS secret from cert/key files
kubectl create secret tls my-tls \
--cert=fullchain.pem \
--key=privkey.pemSecret 清单
data 值必须 base64 编码(echo -n 'value' | base64)。stringData 是接受明文的便捷方式,apply 时合并到 data。type Opaque 是默认;专用类型(kubernetes.io/tls、kubernetes.io/dockerconfigjson)会校验 key。
apiVersion: v1
kind: Secret
metadata:
name: db-creds
type: Opaque
data:
username: YWRtaW4= # base64 of "admin"
password: UzNjdXIzIQ== # base64 of "S3cur3!"
# stringData accepts plaintext (auto-encoded on apply)
stringData:
api-key: "live-key-xyz"
# encode on the command line:
# echo -n 'admin' | base64
# decode:
# echo 'YWRtaW4=' | base64 -d作为环境变量使用 Secret
将 Secret 作为环境变量消费与 ConfigMap 相同,但使用 secretKeyRef/secretRef。注意环境变量可通过 /proc/1/environ 及容器内任何进程可见——高度敏感数据建议改用卷挂载。
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-creds
key: password
envFrom:
- secretRef:
name: db-creds # injects all keys
optional: true作为卷使用 Secret
挂载的 Secret 以文件形式投射到 tmpfs(内存)卷——从不写入节点磁盘。defaultMode 0400 限制访问。挂载的 Secret 在 Secret 变更时( kubelet 同步后)会更新,与环境变量型 Secret 不同。
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: secrets
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secrets
secret:
secretName: db-creds
defaultMode: 0400 # restrict permissions
items:
- key: password
path: db-password # written to /etc/secrets/db-password
# memory-backed tmpfs, never written to disk on the nodeImagePullSecret
imagePullSecrets 在拉取镜像时向私有仓库认证。附加到 ServiceAccount 会自动应用于使用该 SA 的每个 Pod——这是推荐模式。docker-registry secret 类型自动生成正确的 .dockerconfigjson 负载。
# attach to a pod
apiVersion: v1
kind: Pod
metadata:
name: private-app
spec:
imagePullSecrets:
- name: regcred
containers:
- name: app
image: registry.example.com/myapp:1.0
# attach to a service account (auto-applied to all pods using it)
kubectl patch serviceaccount default \
-p '{"imagePullSecrets":[{"name":"regcred"}]}'
# verify
kubectl get sa default -o jsonpath='{.imagePullSecrets}'Secret 类型
专用 secret 类型启用校验和集成:tls 用于 Ingress,dockerconfigjson 用于镜像拉取,service-account-token 自动挂载到 Pod。使用正确类型可确保 key 被校验并被正确的控制器消费。
# Opaque (default) — arbitrary key-value
type: Opaque
# kubernetes.io/service-account-token — auto for SAs
type: kubernetes.io/service-account-token
# kubernetes.io/dockerconfigjson — registry auth
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: <base64>
# kubernetes.io/tls — for Ingress TLS
type: kubernetes.io/tls
data:
tls.crt: <base64>
tls.key: <base64>
# kubernetes.io/basic-auth
type: kubernetes.io/basic-auth
stringData:
username: admin
password: passNamespace
创建 Namespace
Namespace 为多团队或多环境(dev/stage/prod)划分集群。资源名在同一 namespace 内必须唯一。某些资源(Node、PV、StorageClass)是集群作用域,不属于 namespace。
# imperative
kubectl create namespace dev
# declarative
apiVersion: v1
kind: Namespace
metadata:
name: dev
labels:
environment: development
team: platform
# apply
kubectl apply -f namespace.yaml
# list namespaces
kubectl get namespaces
# set default namespace for current context
kubectl config set-context --current --namespace=devResourceQuota
ResourceQuota 限定 namespace 内的资源总用量——CPU/内存 requests/limits 总量、对象计数(Pod、PVC、Service、Deployment)。多租户集群必备,防止一个团队饿死其他团队。设置配额后未显式设 requests 的 Pod 会被拒绝。
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
namespace: dev
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
pods: "50"
services.loadbalancers: "2"
persistentvolumeclaims: "10"
count/deployments.apps: "5"
# limits total aggregate resource use in the namespaceLimitRange
LimitRange 设置单资源的默认值和边界:为未指定的 Pod 提供默认 requests/limits,并用 min/max 约束极端值。与 ResourceQuota 配对——没有默认 requests,配额会拒绝所有忘记设置的 Pod。
apiVersion: v1
kind: LimitRange
metadata:
name: default-limits
namespace: dev
spec:
limits:
- type: Container
default: # default limits (if unset)
cpu: 500m
memory: 512Mi
defaultRequest: # default requests (if unset)
cpu: 100m
memory: 128Mi
max: # max allowed limits
cpu: "2"
memory: 2Gi
min: # min allowed requests
cpu: 50m
memory: 64Mi
- type: PersistentVolumeClaim
max:
storage: 100Gi
min:
storage: 1Gi删除 Namespace 与 Finalizer
删除 namespace 会级联删除其所有资源。卡在 Terminating 的 namespace 通常有无法完成的 finalizer——APIService 不可用(如 metrics-server 被移除)或 CRD 的控制器已消失。移除 finalizer 可强制完成,但可能泄漏外部资源。
# delete a namespace (cascades all resources in it)
kubectl delete namespace dev
# if stuck in Terminating, inspect finalizers
kubectl get namespace dev -o yaml
# remove finalizer to force completion (DANGEROUS)
kubectl patch namespace dev -p '{"metadata":{"finalizers":null}}'
# resources that block deletion:
# - APIService unavailable (metrics-server removed)
# - custom resources whose CRD is gone
# - PVCs with attached PVs
# check what's still in the namespace
kubectl api-resources --verbs=list --namespaced -o name \
| xargs -n 1 kubectl get -n dev --ignore-not-found默认 Namespace
kube-system 运行控制平面和附加组件(DNS、kube-proxy、CNI)。kube-public 存放未认证用户可读的引导数据。kube-node-lease 以 Lease 对象存储节点心跳以提升性能。未指定 namespace 时,工作负载落在 default。
# built-in namespaces
kubectl get namespaces
# NAME STATUS AGE
# default Active 30d <- user workloads land here
# kube-system Active 30d <- control plane / addons
# kube-public Active 30d <- publicly readable (bootstrap)
# kube-node-lease Active 30d <- node heartbeats (leases)
# kube-system holds:
# - kube-dns / CoreDNS
# - kube-proxy
# - metrics-server
# - CNI, CSI, cloud provider controllers
# kube-public is readable by all (used for cluster info discovery)Namespace 作用域 vs 集群作用域
大多数工作负载资源是 namespace 作用域;基础设施(Node、PV、StorageClass、ClusterRole)是集群作用域。Service 只能针对同 namespace 的 Pod。-A 是 --all-namespaces 的简写——对集群全局可见性至关重要。
# which resources are namespaced?
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
# namespaced: pods, services, deployments, configmaps, secrets
# cluster-scoped: nodes, namespaces, PVs, StorageClasses, ClusterRoles
# access across namespaces:
# - a Service selector only matches pods in the SAME namespace
# - cross-namespace refs require special controllers (e.g. external-dns)
# list resources across all namespaces
kubectl get pods --all-namespaces
kubectl get pods -A # shorthand标签与选择器
标签语法
标签是用于识别和分组资源的键值对。key 可有可选前缀(DNS 子域名,如 app.kubernetes.io/)。标签用于查询/过滤,而注解用于任意非标识性元数据。
# labels are key=value pairs
# key: prefix (optional DNS subdomain) + name
# value: string, up to 63 chars
metadata:
labels:
app: nginx
tier: frontend
env: prod
app.kubernetes.io/name: nginx
app.kubernetes.io/version: "1.25"
# view labels
kubectl get pods --show-labels
# add/overwrite a label
kubectl label pod nginx env=prod
kubectl label pod nginx env=staging --overwrite
# remove a label (trailing dash)
kubectl label pod nginx env-等式与集合选择器
两种选择器:等式(=、==、!=)和集合(in、notin、exists、!exists)。多个逗号分隔的条件为 AND。Service 和 Deployment 在 YAML 中用等式选择器;kubectl -l 支持两者。
# equality-based: = == !=
kubectl get pods -l app=nginx
kubectl get pods -l env!=dev
kubectl get pods -l 'app=nginx,env=prod' # AND of conditions
# set-based: in, notin, exists
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'env notin (dev)'
kubectl get pods -l 'tier' # key exists
kubectl get pods -l '!canary' # key does not exist
# combine equality and set-based
kubectl get pods -l 'app=nginx,env in (prod,staging)'为资源打标签
label 修改标识性元数据——用于选择器应匹配的任何内容。annotate 用于非标识性元数据(owner、工单、描述、工具提示)。节点常被标记拓扑或硬件提示来驱动调度。
# label a pod
kubectl label pod nginx app=nginx tier=web
# label all pods matching a selector
kubectl label pods -l app=oldapp app=newapp --overwrite
# label a node (for scheduling hints)
kubectl label node node-1 disktype=ssd
# remove a node label
kubectl label node node-1 disktype-
# list nodes by label
kubectl get nodes -l disktype=ssd
# annotate (non-identifying metadata)
kubectl annotate pod nginx owner=alice
kubectl annotate pod nginx description="web server"清单中的选择器
YAML 中选择器使用 matchLabels(等式)和 matchExpressions(集合,operator 为 In/NotIn/Exists/DoesNotExist)。对 Deployment,选择器创建后不可变——且 Pod 模板标签必须匹配它。Service 仅支持 matchLabels。
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels: # equality-based
app: nginx
matchExpressions: # set-based (optional)
- key: env
operator: In
values: [prod, staging]
- key: tier
operator: Exists
template:
metadata:
labels:
app: nginx # MUST match selector
env: prod
tier: web注解
注解持有工具使用的非标识性元数据——kubectl apply 存储上次应用的配置,cert-manager 读取 issuer 提示,Prometheus 读取采集配置,控制器存储推出状态。与标签不同,注解值可以是大型 JSON 块。
metadata:
annotations:
kubernetes.io/change-cause: "bump nginx to 1.26"
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"apps/v1",...}
cert-manager.io/cluster-issuer: "letsencrypt-prod"
# view annotations
kubectl get pod nginx -o jsonpath='{.metadata.annotations}'
# annotate
kubectl annotate pod nginx owner=team-platform
# remove an annotation (trailing dash)
kubectl annotate pod nginx owner-推荐标签
app.kubernetes.io/* 标签是共享词汇表,让工具(Helm、operator、仪表盘)能将一个应用的所有资源分组。name+instance 唯一标识一个发布;component/part-of 描述层级;managed-by/created-by 跟踪所有权。
# shared recommended labels (app.kubernetes.io/*)
metadata:
labels:
app.kubernetes.io/name: nginx
app.kubernetes.io/instance: nginx-prod
app.kubernetes.io/version: "1.25"
app.kubernetes.io/component: web
app.kubernetes.io/part-of: storefront
app.kubernetes.io/managed-by: helm
app.kubernetes.io/created-by: controller-manager
# Helm applies these automatically; kubectl doesn't.
# They unify how tooling identifies an application's resources
# across Deployments, Services, Ingresses, ConfigMaps, etc.ReplicaSet
ReplicaSet 清单
ReplicaSet 维护一组匹配选择器的稳定副本 Pod——在 Pod 被删除或失败时重建它们。几乎总是用 Deployment 代替,它包装 ReplicaSet 并增加滚动更新和回滚。
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
# kubectl get rs
# kubectl describe rs nginxReplicaSet 工作原理
ReplicaSet 控制器用选择器调和期望与实际 Pod 数。每个 Pod 有指向 RS 的 ownerReference——这就是 kubectl get pod 显示 'Owned by ReplicaSet/nginx' 的原因。扩缩容只是改变期望数。
# the controller loop:
# 1. count pods matching selector
# 2. if fewer than replicas -> create from template
# 3. if more than replicas -> delete excess (arbitrary order)
# owned-by reference on each pod
kubectl get pod -l app=nginx -o jsonpath='{.items[*].metadata.ownerReferences}'
# if you delete a pod, the RS creates a new one immediately
kubectl delete pod <pod-name>
kubectl get pods -l app=nginx
# scale by editing replicas
kubectl scale rs nginx --replicas=5ReplicaSet vs ReplicationController
ReplicationController(原始 v1 原语)仅支持等式选择器,已弃用。ReplicaSet(apps/v1)增加集合选择器。实践中应使用 Deployment——它替你管理 ReplicaSet 并提供滚动更新/回滚。
# ReplicationController (v1, legacy): equality-only selectors
# ReplicaSet (apps/v1, modern): set-based selectors (in, notin, exists)
# ReplicationController is deprecated; do not use.
apiVersion: v1
kind: ReplicationController # legacy
# ...
# ReplicaSet is the successor:
apiVersion: apps/v1
kind: ReplicaSet # modern
# ...
# Deployment wraps ReplicaSet and is the recommended primitive:
apiVersion: apps/v1
kind: Deployment # use this in practice手动扩缩容
kubectl scale 修改 replicas 字段。如果 HPA 针对同一资源,它会在下次调和中覆盖手动扩缩。一次性操作优先用 kubectl scale,持续弹性工作负载用 HPA。
# scale a replicaset directly
kubectl scale rs nginx --replicas=5
# scale via patch
kubectl patch rs nginx -p '{"spec":{"replicas":5}}'
# scale multiple resources at once
kubectl scale deployment nginx deployment web --replicas=3
# scale by referencing a file
kubectl scale --replicas=5 -f nginx.yaml
# the autoscaler (HPA) will override manual scaling
# if it targets the same resource模板变更与接管
与 Deployment 不同,裸 ReplicaSet 不会推出 Pod 模板变更——只有新创建的 Pod(删除/扩容后)才用新规格。ReplicaSet 会接管匹配其选择器的任何孤立 Pod,这可能导致意外行为。
# changing the pod template does NOT update existing pods
# (unlike a Deployment, a bare ReplicaSet won't roll out)
kubectl edit rs nginx # change image -> new pods use it, old ones don't
# delete old pods to force them onto the new template
kubectl delete pods -l app=nginx
# a ReplicaSet will ADOPT existing pods that match its selector
# even pods created independently — useful (and dangerous)
# orphaned pods (no owner) matching the selector are taken over
kubectl get pods -l app=nginx --show-kind从 ReplicaSet 移除 Pod
要删除 Pod 而不让 ReplicaSet 重建它,要么先把 RS 缩到 0,要么清除 Pod 的 ownerReferences 使 RS 不再拥有它。用于调试特定实例或在清理前提取日志。
# detaching a pod from its ReplicaSet (so it isn't replaced)
kubectl patch pod <pod-name> \
-p '{"metadata":{"ownerReferences":[]}}'
# now deleting this pod won't trigger a replacement,
# because the RS no longer owns it
# or scale the RS to 0 first, then delete
kubectl scale rs nginx --replicas=0
kubectl delete pod <pod-name>
# useful for debugging a specific failing pod instance
# without the RS immediately recreating itStatefulSet
StatefulSet 清单
StatefulSet 为 Pod 提供稳定标识(名、主机名、存储)和有序的部署/扩缩。需要 headless serviceName。volumeClaimTemplates 为每个 Pod 创建专用 PVC——所以即使 pod-0 被重新调度,它也会重新挂载同一卷。
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
serviceName: mysql # required: headless service
replicas: 3
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:8
ports:
- containerPort: 3306
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumeClaimTemplates: # one PVC per pod
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi稳定标识
每个 Pod 有稳定的序号名(mysql-0、mysql-1、…)和通过 headless service 的稳定 DNS 名。节点故障时,pod-0 被调度到别处但保留名称并重新挂载卷——对依赖稳定成员关系的集群数据库至关重要。
# pods are named <statefulset-name>-<ordinal>
# mysql-0, mysql-1, mysql-2
kubectl get pods -l app=mysql
# each pod has stable DNS (via the headless service):
# mysql-0.mysql.default.svc.cluster.local
# mysql-1.mysql.default.svc.cluster.local
# stable hostname inside the pod:
kubectl exec mysql-0 -- hostname
# -> mysql-0
# ordinal index also exposed:
kubectl exec mysql-0 -- sh -c 'echo $HOSTNAME'
# -> mysql-0
# pod identity persists across reschedules稳定存储
volumeClaimTemplates 为每个 Pod 生成一个可预测名称的 PVC(data-mysql-0、…)。PVC 在 Pod 和 StatefulSet 删除后仍存在——这防止数据丢失,但也意味着必须显式删除 PVC 才能回收存储。同一卷总是重新挂载到同一序号 Pod。
# one PVC per pod, named <volumeClaimTemplate-name>-<pod-name>
kubectl get pvc
# NAME STATUS VOLUME CAPACITY ...
# data-mysql-0 Bound pvc-aaa 10Gi
# data-mysql-1 Bound pvc-bbb 10Gi
# data-mysql-2 Bound pvc-ccc 10Gi
# when pod-0 is rescheduled, it re-binds data-mysql-0
# deleting the StatefulSet does NOT delete PVCs by default
# (protects from accidental data loss)
# to actually delete the data:
kubectl delete pvc data-mysql-0 data-mysql-1 data-mysql-2有序部署与 Pod 管理
OrderedReady(默认)严格按 0→1→2 顺序创建 Pod,按相反顺序删除——需要主节点先于副本引导的系统需要此模式。Parallel 同时创建/删除所有 Pod——对对称分片存储(Cassandra、Elasticsearch)更快。
spec:
podManagementPolicy: OrderedReady # default: strict order
# podManagementPolicy: Parallel # create/delete all at once
replicas: 3
# OrderedReady: create pod-0, then pod-1, then pod-2 (each waits for Ready)
# deletion is reverse: pod-2, pod-1, pod-0
# Parallel: all pods created/deleted simultaneously
# identity and storage remain stable either way
# check policy
kubectl get statefulset mysql -o jsonpath='{.spec.podManagementPolicy}'
# parallel is great for sharded stores that don't need bootstrap order滚动更新
StatefulSet 滚动更新按逆序(N-1 到 0)进行。partition 让你先金丝雀最高序号的 Pod。OnDelete 暂停更新直到你手动删除 Pod——用于受控迁移。由于有序性,推出比 Deployment 慢。
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2 # only pods with ordinal >= 2 update
maxUnavailable: 1 # (default 1) allowed down
# type: OnDelete -> only update when pod is manually deleted
# partition enables canaries: set partition=N to update
# only the top N pods; lower to 0 to roll out to all.
kubectl rollout status statefulset/mysql
# waits for all pods to be updated
# StatefulSets also support rollout history/undo,
# but only when the change is in the pod templateHeadless Service 关联
spec.serviceName 引用的 headless service(clusterIP: None)是使稳定每 Pod DNS 工作的关键。没有它 StatefulSet 不会创建 Pod。客户端解析 service 名获得轮询,或 pod-0.svc 固定到主节点。别忘了创建 Service。
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
clusterIP: None # headless
selector:
app: mysql
ports:
- port: 3306
---
# StatefulSet references this service via spec.serviceName
# this gives each pod a stable DNS:
# mysql-0.mysql.default.svc.cluster.local
# clients can:
# - resolve mysql -> any pod IP (load-balanced by DNS round-robin)
# - resolve mysql-0.mysql -> pod-0's IP (pin to a specific replica)
# required: serviceName MUST match the headless service nameDaemonSet
DaemonSet 清单
DaemonSet 在每个(匹配调度约束的)节点上运行恰好一个 Pod。适合节点级代理:日志采集、监控、存储、CNI、Ingress 控制器。新节点自动获得 Pod;删除节点时其 Pod 被垃圾回收。