Kubernetes
综合前面所有知识,从零部署一个完整的微服务应用到Kubernetes集群。
# namespace.yaml ✅
apiVersion: v1
kind: Namespace
metadata:
name: ecommerce
---
# frontend-deployment.yaml ✅
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
namespace: ecommerce
spec:
replicas: 2
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: frontend
image: myregistry.com/ecommerce/frontend:v1.0
ports:
- containerPort: 80
resources:
limits: { cpu: 200m, memory: 128Mi }
requests: { cpu: 50m, memory: 64Mi }
livenessProbe:
httpGet: { path: /, port: 80 }
initialDelaySeconds: 10
readinessProbe:
httpGet: { path: /, port: 80 }
initialDelaySeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: frontend-service
namespace: ecommerce
spec:
selector:
app: frontend
ports:
- port: 80
targetPort: 80
---
# api-deployment.yaml ✅
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-gateway
namespace: ecommerce
spec:
replicas: 3
selector:
matchLabels:
app: api-gateway
template:
metadata:
labels:
app: api-gateway
spec:
containers:
- name: api
image: myregistry.com/ecommerce/api-gateway:v1.0
ports:
- containerPort: 8000
env:
- name: USER_SERVICE_URL
value: "http://user-service:8001"
- name: PRODUCT_SERVICE_URL
value: "http://product-service:8002"
- name: ORDER_SERVICE_URL
value: "http://order-service:8003"
- name: JWT_SECRET
valueFrom:
secretKeyRef:
name: app-secrets
key: jwt-secret
resources:
limits: { cpu: 500m, memory: 256Mi }
requests: { cpu: 100m, memory: 128Mi }
livenessProbe:
httpGet: { path: /health, port: 8000 }
readinessProbe:
httpGet: { path: /ready, port: 8000 }
---
# ingress.yaml ✅
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ecommerce-ingress
namespace: ecommerce
annotations:
nginx.ingress.kubernetes.io/rate-limit: "100"
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
ingressClassName: nginx
tls:
- hosts: [app.example.com, api.example.com]
secretName: ecommerce-tls
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: frontend-service
port: { number: 80 }
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api-gateway-service
port: { number: 8000 }
# 1. 创建命名空间 ✅
kubectl apply -f namespace.yaml
# 2. 创建Secret ✅
kubectl create secret generic app-secrets \
--namespace ecommerce \
--from-literal=jwt-secret=$(openssl rand -base64 32) \
--from-literal=db-password=$(openssl rand -base64 16)
# 3. 部署数据库(使用Helm)✅
helm install postgres bitnami/postgresql \
--namespace ecommerce \
--set auth.username=app \
--set auth.password=$(kubectl get secret app-secrets -n ecommerce -o jsonpath='{.data.db-password}' | base64 -d) \
--set primary.persistence.size=10Gi
# 4. 部署应用 ✅
kubectl apply -f frontend-deployment.yaml
kubectl apply -f api-deployment.yaml
kubectl apply -f user-service.yaml
kubectl apply -f product-service.yaml
kubectl apply -f order-service.yaml
kubectl apply -f ingress.yaml
# 5. 验证 ✅
kubectl get pods -n ecommerce
kubectl get ingress -n ecommerce
# 6. 测试 ✅
curl https://app.example.com
curl https://api.example.com/health
# GitHub Actions完整流水线 ✅
name: Deploy
on:
push:
branches: [main]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# 构建并推送镜像
- name: Build & Push
run: |
docker build -t myregistry.com/ecommerce/api:${{ github.sha }} ./api
docker push myregistry.com/ecommerce/api:${{ github.sha }}
# 安全扫描
- name: Security Scan
uses: aquasecurity/trivy-action@master
with:
image-ref: 'myregistry.com/ecommerce/api:${{ github.sha }}'
severity: 'CRITICAL,HIGH'
exit-code: '1'
# 部署到K8s
- name: Deploy
run: |
kubectl set image deployment/api-gateway \
api=myregistry.com/ecommerce/api:${{ github.sha }} \
-n ecommerce
kubectl rollout status deployment/api-gateway -n ecommerce --timeout=300s
35课的旅程到此结束。回顾一下我们学到的:
| 阶段 | 课程 | 核心技能 |
|---|---|---|
| Docker基础 | 01-07 | 容器概念、安装、镜像、生命周期、网络、数据卷、Dockerfile |
| 镜像构建 | 08-14 | 多阶段构建、优化、缓存、私有仓库、安全扫描、版本管理、最佳实践 |
| Docker Compose | 15-21 | 服务编排、网络、持久化、环境变量、开发/测试环境 |
| 生产部署 | 22-28 | 监控、日志、健康检查、资源限制、滚动更新、回滚、安全加固 |
| Kubernetes | 29-35 | K8s概念、Pod/Deployment、Service/Ingress、ConfigMap/Secret、Helm、监控、全栈部署 |
🎉 恭喜完成全部35课!你已经掌握了从Docker基础到Kubernetes生产部署的完整知识体系。
继续学习的方向:服务网格(Istio)、GitOps(ArgoCD)、平台工程、混沌工程。容器化的世界永无止境!
❓ 生产K8s集群该自己搭建还是用托管服务?95%的场景用托管服务(EKS/GKE/AKS)。自建集群只在:①特殊合规要求 ②成本极端敏感 ③需要深度定制。托管服务省去大量运维负担,让你专注于应用。
| 要点 | 说明 | 最佳实践 |
|---|---|---|
| 资源规划 | 根据业务负载合理分配CPU/内存 | 先压测再上线,设置requests和limits |
| 监控告警 | 设置关键指标阈值和告警规则 | Prometheus + AlertManager,5分钟P99延迟告警 |
| 备份策略 | 定期备份关键数据和配置 | 自动化备份脚本 + 异地存储 + 定期恢复演练 |
| 灰度发布 | 新版本逐步放量降低风险 | 金丝雀发布5%→20%→50%→100% |
| 回滚预案 | 部署前确认回滚方案和步骤 | 保留前一版本镜像,数据库迁移向前兼容 |
| 文档更新 | 配置变更必须同步更新文档 | GitOps管理配置,变更即文档 |
| 安全基线 | 遵循CIS Docker Benchmark | 非root运行、只读FS、最小能力 |
| 日志规范 | 结构化日志,统一格式 | JSON格式日志,包含traceId |
# 容器生命周期
docker create/start/stop/restart/rm/pause/unpause
docker logs/top/stats/inspect/exec diff
# 镜像构建
docker build/pull/push/tag/rmi/images/history
docker save/load/import/manifest
# 网络与存储
docker network create/ls/inspect/connect/disconnect/rm/prune
docker volume create/ls/inspect/rm/prune
# Docker Compose
docker compose up/down/ps/logs/build/exec
docker compose config/stop/start/scale/top/cp
# 系统维护
docker system df/prune/info
docker builder prune
docker container/prune/image prune
# K8s常用命令
kubectl get/describe/logs/exec/apply/delete
kubectl rollout status/undo/history
kubectl scale/autoscale/set