2449 字
12 分钟
Kubernetes 入门到实战完全指南:从核心概念到生产部署 | 2026最新实践
Kubernetes(K8s)是当今最流行的容器编排平台,是云原生应用的事实标准。无论是微服务部署、自动扩缩容还是滚动更新,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 副本,滚动更新 | 进程管理器 |
| Service | Pod 的稳定网络入口 | 负载均衡器 |
| Ingress | HTTP 路由入口 | Nginx 反向代理 |
| ConfigMap | 非敏感配置 | 配置文件 |
| Secret | 敏感配置 | 密码库 |
| Volume | 数据持久化 | 磁盘 |
| Namespace | 资源隔离 | 文件夹 |
二、本地环境搭建
2.1 安装 Minikube
# macOSbrew install minikube
# Linuxcurl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64sudo install minikube-linux-amd64 /usr/local/bin/minikube
# Windowschoco install minikube2.2 启动集群
# 启动(默认使用 Docker 驱动)minikube start
# 指定资源minikube start --cpus=4 --memory=8192
# 查看状态minikube status
# 打开 Dashboardminikube dashboard
# 停止minikube stop
# 删除minikube delete2.3 安装 kubectl
# macOSbrew install kubectl
# Linuxcurl -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 --clientkubectl cluster-infokubectl get nodes三、kubectl 命令速查
3.1 基础命令
# 查看资源kubectl get pods # 查看 Podkubectl get deployments # 查看 Deploymentkubectl get services # 查看 Servicekubectl 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/bashkubectl exec -it <pod-name> -- /bin/sh
# 端口转发kubectl port-forward <pod-name> 8080:803.2 创建与删除
# 创建kubectl create deployment nginx --image=nginx:latestkubectl create deployment web --image=nginx --replicas=3
# 扩缩容kubectl scale deployment nginx --replicas=5
# 暴露服务kubectl expose deployment nginx --port=80 --type=NodePortkubectl expose deployment nginx --port=80 --type=LoadBalancer
# 删除kubectl delete deployment nginxkubectl delete service nginxkubectl delete pod <pod-name>kubectl delete -f deployment.yaml3.3 应用与更新
# 应用 YAMLkubectl apply -f deployment.yamlkubectl apply -f ./manifests/ # 目录下所有 YAML
# 滚动更新kubectl set image deployment/nginx nginx=nginx:1.25
# 回滚kubectl rollout undo deployment/nginxkubectl rollout status deployment/nginxkubectl rollout history deployment/nginx
# 编辑kubectl edit deployment nginx
# 标签kubectl label pod <pod-name> env=prodkubectl get pods -l env=prod四、YAML 配置
4.1 Deployment
apiVersion: apps/v1kind: Deploymentmetadata: name: web-app labels: app: webspec: 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: 34.2 Service
apiVersion: v1kind: Servicemetadata: name: web-servicespec: type: ClusterIP # ClusterIP / NodePort / LoadBalancer selector: app: web ports: - port: 80 # Service 端口 targetPort: 80 # Pod 端口 protocol: TCP4.3 Ingress
apiVersion: networking.k8s.io/v1kind: Ingressmetadata: 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
apiVersion: v1kind: ConfigMapmetadata: name: app-configdata: 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/v1kind: Deploymentmetadata: name: appspec: 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-config5.2 Secret
# 创建 Secretkubectl 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.pemapiVersion: v1kind: Secretmetadata: name: db-secrettype: Opaquedata: username: YWRtaW4= # base64(admin) password: TXlTZWNyZXQxMjM= # base64(MySecret123)# 使用 SecretapiVersion: apps/v1kind: Deploymentspec: template: spec: containers: - name: app env: - name: DB_PASSWORD valueFrom: secretKeyRef: name: db-secret key: password六、存储管理
6.1 PersistentVolume 和 PersistentVolumeClaim
# pv.yaml - 持久化卷apiVersion: v1kind: PersistentVolumemetadata: name: data-pvspec: capacity: storage: 10Gi accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Retain hostPath: path: /mnt/data# pvc.yaml - 持久化卷声明apiVersion: v1kind: PersistentVolumeClaimmetadata: name: data-pvcspec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi# 在 Pod 中使用apiVersion: apps/v1kind: Deploymentspec: template: spec: containers: - name: app image: mysql:8 volumeMounts: - name: data mountPath: /var/lib/mysql volumes: - name: data persistentVolumeClaim: claimName: data-pvc6.2 StorageClass(动态供给)
apiVersion: storage.k8s.io/v1kind: StorageClassmetadata: name: fast-storageprovisioner: kubernetes.io/aws-ebsparameters: type: gp3 fsType: ext4reclaimPolicy: RetainvolumeBindingMode: WaitForFirstConsumer七、健康检查
7.1 三种探针
apiVersion: apps/v1kind: Deploymentspec: 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: 107.2 探针类型
| 类型 | 说明 | 适用场景 |
|---|---|---|
| httpGet | HTTP 请求,2xx-3xx 为成功 | Web 应用 |
| tcpSocket | TCP 连接成功即为成功 | 数据库 |
| exec | 执行命令,退出码 0 为成功 | 自定义检查 |
八、自动扩缩容(HPA)
8.1 安装 Metrics Server
# Minikubeminikube addons enable metrics-server
# 生产环境kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml8.2 配置 HPA
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: web-hpaspec: 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% 扩容# 应用kubectl apply -f hpa.yaml
# 查看kubectl get hpakubectl describe hpa web-hpa九、Helm 包管理
9.1 安装 Helm
# macOSbrew install helm
# Linuxcurl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash9.2 使用 Helm
# 添加仓库helm repo add bitnami https://charts.bitnami.com/bitnamihelm repo update
# 搜索helm search repo nginx
# 安装helm install my-nginx bitnami/nginx
# 查看helm listhelm status my-nginx
# 卸载helm uninstall my-nginx9.3 自定义 Chart
# 创建 Charthelm create myapp
# 目录结构# myapp/# ├── Chart.yaml# ├── values.yaml# ├── templates/# │ ├── deployment.yaml# │ ├── service.yaml# │ └── ingress.yaml# └── .helmignorereplicaCount: 3image: repository: myapp tag: latest pullPolicy: IfNotPresentservice: type: ClusterIP port: 80resources: limits: cpu: 200m memory: 256Mi requests: cpu: 100m memory: 128Mi# 渲染模板(预览)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/v1kind: Deploymentspec: 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 监控与日志
# 安装 Prometheus + Grafanahelm repo add prometheus-community https://prometheus-community.github.io/helm-chartshelm install monitoring prometheus-community/kube-prometheus-stack
# 端口转发访问 Grafanakubectl port-forward svc/monitoring-grafana 3000:80
# 安装 Loki 日志系统helm repo add grafana https://grafana.github.io/helm-chartshelm install loki grafana/loki-stack十一、常见问题
Q1: Pod 一直处于 Pending 状态?
# 查看 Pod 事件kubectl describe pod <pod-name>
# 常见原因:# 1. 资源不足 → 调整 requests 或扩容节点# 2. 没有匹配的节点 → 检查 nodeSelector/tolerations# 3. PVC 未绑定 → 检查 StorageClass# 4. 镜像拉取失败 → 检查镜像名称和拉取凭证Q2: Pod 一直 CrashLoopBackOff?
# 查看日志kubectl logs <pod-name>kubectl logs <pod-name> --previous
# 常见原因:# 1. 应用启动失败 → 查看日志# 2. 健康检查失败 → 调整 initialDelaySeconds# 3. 配置错误 → 检查 ConfigMap/Secret# 4. 权限问题 → 检查 securityContextQ3: Service 无法访问 Pod?
# 1. 检查 Endpointkubectl get endpoints <service-name>
# 2. 检查标签匹配kubectl get pods --show-labelskubectl get svc <service-name> -o yaml
# 3. 检查 readinessProbekubectl 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 |
| Ingress | HTTP 路由 | 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/