2449 字
12 分钟

Kubernetes 入门到实战完全指南:从核心概念到生产部署 | 2026最新实践

Kubernetes(K8s)是当今最流行的容器编排平台,是云原生应用的事实标准。无论是微服务部署、自动扩缩容还是滚动更新,Kubernetes 都提供了强大的能力。本文从核心概念到生产部署,帮助你快速掌握 Kubernetes。

Kubernetes 入门到实战

本文内容包括:

  • Kubernetes 核心概念(Pod / Deployment / Service / Ingress)
  • Minikube 本地环境搭建
  • kubectl 命令速查
  • YAML 配置文件编写
  • 滚动更新与回滚
  • ConfigMap / Secret 配置管理
  • 存储卷(PV / PVC / StorageClass)
  • 健康检查与自动恢复
  • HPA 自动扩缩容
  • Helm 包管理
  • 生产环境最佳实践

一、Kubernetes 核心概念#

1.1 架构总览#

┌─────────────────────────────────────────────┐
│ Kubernetes Cluster │
│ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Master Node │ │ Worker Nodes │ │
│ │ │ │ │ │
│ │ • API Server │ │ ┌─────────────┐ │ │
│ │ • Scheduler │ │ │ kubelet │ │ │
│ │ • Controller │ │ │ kube-proxy │ │ │
│ │ • etcd │ │ │ Container │ │ │
│ │ │ │ │ Runtime │ │ │
│ │ │ │ │ (Pods) │ │ │
│ │ │ │ └─────────────┘ │ │
│ └──────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────┘

1.2 核心对象#

对象说明类比
Pod最小调度单元,含 1+ 容器虚拟机上的进程
Deployment管理 Pod 副本,滚动更新进程管理器
ServicePod 的稳定网络入口负载均衡器
IngressHTTP 路由入口Nginx 反向代理
ConfigMap非敏感配置配置文件
Secret敏感配置密码库
Volume数据持久化磁盘
Namespace资源隔离文件夹

二、本地环境搭建#

2.1 安装 Minikube#

Terminal window
# macOS
brew install minikube
# Linux
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube
# Windows
choco install minikube

2.2 启动集群#

Terminal window
# 启动(默认使用 Docker 驱动)
minikube start
# 指定资源
minikube start --cpus=4 --memory=8192
# 查看状态
minikube status
# 打开 Dashboard
minikube dashboard
# 停止
minikube stop
# 删除
minikube delete

2.3 安装 kubectl#

Terminal window
# macOS
brew install kubectl
# Linux
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install kubectl /usr/local/bin/kubectl
# 验证
kubectl version --client
kubectl cluster-info
kubectl get nodes

三、kubectl 命令速查#

3.1 基础命令#

Terminal window
# 查看资源
kubectl get pods # 查看 Pod
kubectl get deployments # 查看 Deployment
kubectl get services # 查看 Service
kubectl get all # 查看所有资源
kubectl get pods -o wide # 详细信息
kubectl get pods --show-labels # 显示标签
# 命名空间
kubectl get pods -n kube-system # 指定命名空间
kubectl get pods --all-namespaces # 所有命名空间
kubectl create namespace dev # 创建命名空间
# 详情
kubectl describe pod <pod-name> # 查看 Pod 详情
kubectl logs <pod-name> # 查看日志
kubectl logs -f <pod-name> # 跟踪日志
kubectl logs <pod-name> -c <container> # 指定容器
# 进入容器
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -- /bin/sh
# 端口转发
kubectl port-forward <pod-name> 8080:80

3.2 创建与删除#

Terminal window
# 创建
kubectl create deployment nginx --image=nginx:latest
kubectl create deployment web --image=nginx --replicas=3
# 扩缩容
kubectl scale deployment nginx --replicas=5
# 暴露服务
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# 删除
kubectl delete deployment nginx
kubectl delete service nginx
kubectl delete pod <pod-name>
kubectl delete -f deployment.yaml

3.3 应用与更新#

Terminal window
# 应用 YAML
kubectl apply -f deployment.yaml
kubectl apply -f ./manifests/ # 目录下所有 YAML
# 滚动更新
kubectl set image deployment/nginx nginx=nginx:1.25
# 回滚
kubectl rollout undo deployment/nginx
kubectl rollout status deployment/nginx
kubectl rollout history deployment/nginx
# 编辑
kubectl edit deployment nginx
# 标签
kubectl label pod <pod-name> env=prod
kubectl get pods -l env=prod

四、YAML 配置#

4.1 Deployment#

deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
labels:
app: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "200m"
memory: "256Mi"
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 10
periodSeconds: 5
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 3

4.2 Service#

service.yaml
apiVersion: v1
kind: Service
metadata:
name: web-service
spec:
type: ClusterIP # ClusterIP / NodePort / LoadBalancer
selector:
app: web
ports:
- port: 80 # Service 端口
targetPort: 80 # Pod 端口
protocol: TCP

4.3 Ingress#

ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls:
- hosts:
- example.com
secretName: tls-secret
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
- path: /api
pathType: Prefix
backend:
service:
name: api-service
port:
number: 8080

五、配置管理#

5.1 ConfigMap#

configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
DATABASE_HOST: "mysql.default.svc.cluster.local"
DATABASE_PORT: "3306"
REDIS_HOST: "redis.default.svc.cluster.local"
LOG_LEVEL: "info"
config.yaml: |
server:
port: 8080
timeout: 30s
database:
max_connections: 20
# 在 Deployment 中使用
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
spec:
template:
spec:
containers:
- name: app
image: myapp:latest
envFrom:
- configMapRef:
name: app-config # 所有键值对作为环境变量
env:
- name: DB_HOST # 单个引用
valueFrom:
configMapKeyRef:
name: app-config
key: DATABASE_HOST
volumeMounts:
- name: config-volume
mountPath: /etc/config # 挂载为文件
volumes:
- name: config-volume
configMap:
name: app-config

5.2 Secret#

Terminal window
# 创建 Secret
kubectl create secret generic db-secret \
--from-literal=username=admin \
--from-literal=password=MySecret123
# 从文件创建
kubectl create secret generic tls-secret \
--from-file=tls.crt=cert.pem \
--from-file=tls.key=key.pem
secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
username: YWRtaW4= # base64(admin)
password: TXlTZWNyZXQxMjM= # base64(MySecret123)
# 使用 Secret
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: app
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password

六、存储管理#

6.1 PersistentVolume 和 PersistentVolumeClaim#

# pv.yaml - 持久化卷
apiVersion: v1
kind: PersistentVolume
metadata:
name: data-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
hostPath:
path: /mnt/data
# pvc.yaml - 持久化卷声明
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: data-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
# 在 Pod 中使用
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: app
image: mysql:8
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumes:
- name: data
persistentVolumeClaim:
claimName: data-pvc

6.2 StorageClass(动态供给)#

storage-class.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: fast-storage
provisioner: kubernetes.io/aws-ebs
parameters:
type: gp3
fsType: ext4
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer

七、健康检查#

7.1 三种探针#

apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: app
image: myapp:latest
# 存活探针:失败则重启容器
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30 # 启动后 30s 开始检测
periodSeconds: 10 # 每 10s 检测一次
failureThreshold: 3 # 连续失败 3 次重启
# 就绪探针:失败则从 Service 移除
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
# 启动探针:成功后才启动 liveness/readiness
startupProbe:
httpGet:
path: /health
port: 8080
failureThreshold: 30 # 最多等 5 分钟(30 * 10s)
periodSeconds: 10

7.2 探针类型#

类型说明适用场景
httpGetHTTP 请求,2xx-3xx 为成功Web 应用
tcpSocketTCP 连接成功即为成功数据库
exec执行命令,退出码 0 为成功自定义检查

八、自动扩缩容(HPA)#

8.1 安装 Metrics Server#

Terminal window
# Minikube
minikube addons enable metrics-server
# 生产环境
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

8.2 配置 HPA#

hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # CPU 使用率超 70% 扩容
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80 # 内存使用率超 80% 扩容
Terminal window
# 应用
kubectl apply -f hpa.yaml
# 查看
kubectl get hpa
kubectl describe hpa web-hpa

九、Helm 包管理#

9.1 安装 Helm#

Terminal window
# macOS
brew install helm
# Linux
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

9.2 使用 Helm#

Terminal window
# 添加仓库
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
# 搜索
helm search repo nginx
# 安装
helm install my-nginx bitnami/nginx
# 查看
helm list
helm status my-nginx
# 卸载
helm uninstall my-nginx

9.3 自定义 Chart#

Terminal window
# 创建 Chart
helm create myapp
# 目录结构
# myapp/
# ├── Chart.yaml
# ├── values.yaml
# ├── templates/
# │ ├── deployment.yaml
# │ ├── service.yaml
# │ └── ingress.yaml
# └── .helmignore
values.yaml
replicaCount: 3
image:
repository: myapp
tag: latest
pullPolicy: IfNotPresent
service:
type: ClusterIP
port: 80
resources:
limits:
cpu: 200m
memory: 256Mi
requests:
cpu: 100m
memory: 128Mi
Terminal window
# 渲染模板(预览)
helm template myapp ./myapp
# 安装
helm install myapp ./myapp
# 升级
helm upgrade myapp ./myapp
# 带自定义值
helm install myapp ./myapp -f custom-values.yaml

十、生产环境最佳实践#

10.1 安全加固#

# Pod 安全上下文
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
securityContext:
runAsNonRoot: true # 非 root 运行
runAsUser: 1000
fsGroup: 2000
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true # 只读根文件系统
capabilities:
drop:
- ALL # 删除所有能力

10.2 资源管理#

# 必须设置资源限制
containers:
- name: app
resources:
requests: # 调度依据
cpu: "100m" # 0.1 核
memory: "128Mi"
limits: # 硬限制
cpu: "500m"
memory: "512Mi"

10.3 生产检查清单#

✅ 资源限制:所有容器设置 requests 和 limits
✅ 健康检查:配置 livenessProbe 和 readinessProbe
✅ 副本数:至少 2 个副本
✅ 镜像:使用固定版本,非 latest
✅ 配置分离:ConfigMap + Secret
✅ 持久化:有状态服务使用 PVC
✅ 自动扩缩容:配置 HPA
✅ 安全:非 root 运行,readOnlyRootFilesystem
✅ RBAC:最小权限原则
✅ 网络策略:NetworkPolicy 限制通信
✅ 监控:Prometheus + Grafana
✅ 日志:集中收集(ELK / Loki)
✅ 备份:定期备份 etcd 和 PV
✅ 版本:Kubernetes 版本跟随社区
✅ 多可用区:Pod 跨可用区分布

10.4 监控与日志#

Terminal window
# 安装 Prometheus + Grafana
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install monitoring prometheus-community/kube-prometheus-stack
# 端口转发访问 Grafana
kubectl port-forward svc/monitoring-grafana 3000:80
# 安装 Loki 日志系统
helm repo add grafana https://grafana.github.io/helm-charts
helm install loki grafana/loki-stack

十一、常见问题#

Q1: Pod 一直处于 Pending 状态?#

Terminal window
# 查看 Pod 事件
kubectl describe pod <pod-name>
# 常见原因:
# 1. 资源不足 → 调整 requests 或扩容节点
# 2. 没有匹配的节点 → 检查 nodeSelector/tolerations
# 3. PVC 未绑定 → 检查 StorageClass
# 4. 镜像拉取失败 → 检查镜像名称和拉取凭证

Q2: Pod 一直 CrashLoopBackOff?#

Terminal window
# 查看日志
kubectl logs <pod-name>
kubectl logs <pod-name> --previous
# 常见原因:
# 1. 应用启动失败 → 查看日志
# 2. 健康检查失败 → 调整 initialDelaySeconds
# 3. 配置错误 → 检查 ConfigMap/Secret
# 4. 权限问题 → 检查 securityContext

Q3: Service 无法访问 Pod?#

Terminal window
# 1. 检查 Endpoint
kubectl get endpoints <service-name>
# 2. 检查标签匹配
kubectl get pods --show-labels
kubectl get svc <service-name> -o yaml
# 3. 检查 readinessProbe
kubectl describe pod <pod-name>
# 4. DNS 解析
kubectl exec -it <pod-name> -- nslookup <service-name>

十二、总结#

Kubernetes 学习路径#

入门 → 进阶 → 生产
│ │ │
│ │ ├── 安全加固(RBAC/NetworkPolicy)
│ │ ├── 监控告警(Prometheus/Grafana)
│ │ ├── 日志收集(ELK/Loki)
│ │ └── CI/CD(ArgoCD/Flux)
│ │
│ ├── StatefulSet(有状态应用)
│ ├── DaemonSet(节点守护进程)
│ ├── Job/CronJob(批处理任务)
│ ├── RBAC(权限管理)
│ └── 网络策略(NetworkPolicy)
├── 核心概念(Pod/Deployment/Service)
├── kubectl 命令
├── YAML 编写
├── ConfigMap/Secret
└── Minikube 实践

核心对象速查#

对象用途关键字段
Pod运行容器containers, volumes
Deployment管理副本replicas, strategy
Service网络入口type, ports, selector
IngressHTTP 路由rules, tls
ConfigMap配置data
Secret敏感数据data (base64)
PVC存储storage, accessModes
HPA自动扩缩minReplicas, maxReplicas

Kubernetes 是云原生时代的操作系统。它将基础设施抽象为声明式 API,让开发者专注于应用本身。虽然学习曲线陡峭,但掌握后能极大提升部署效率和系统可靠性。2026 年,Kubernetes 已成为容器编排的事实标准,是每一位后端工程师和运维工程师的必备技能。

Kubernetes 入门到实战完全指南:从核心概念到生产部署 | 2026最新实践
https://971918.xyz/posts/docs/kubernetes-complete-guide/
作者
九所长
发布于
2026-07-24
许可协议
CC BY-NC-SA 4.0