Kubernetes
定义
Kubernetes (K8s) 是 Google 开源的容器编排系统,用于自动化部署、扩展和管理容器化应用程序。
核心概念
Pod
- 最小的部署单元
- 可以包含一个或多个容器
- 共享网络和存储
Deployment
- 管理 Pod 的副本集
- 支持滚动更新和回滚
- 声明式配置
Service
- 提供稳定的网络访问入口
- 负载均衡
- 服务发现
ConfigMap & Secret
- ConfigMap:存储非敏感配置数据
- Secret:存储敏感数据(密码、密钥等)
基础配置文件
Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:latest
ports:
- containerPort: 8000
Service
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
ports:
- port: 80
targetPort: 8000
type: LoadBalancer
健康检查
存活探针(Liveness Probe)
检测容器是否运行正常,失败则重启容器。
就绪探针(Readiness Probe)
检测容器是否准备好接收流量,失败则从 Service 端点移除。
livenessProbe:
httpGet:
path: /health/live
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
readinessProbe:
httpGet:
path: /health/ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 5
常用命令
# 应用配置
kubectl apply -f deployment.yaml
# 查看 Pod
kubectl get pods
# 查看日志
kubectl logs <pod-name>
# 进入容器
kubectl exec -it <pod-name> -- /bin/bash
# 扩展副本数
kubectl scale deployment myapp --replicas=5
# 查看 Service
kubectl get svc
# 端口转发
kubectl port-forward pod/myapp 8000:8000
优势
- 自动扩缩容:根据负载自动调整 Pod 数量
- 自愈能力:自动重启失败的容器
- 滚动更新:零停机部署
- 服务发现:自动配置服务间通信
- 存储编排:支持多种存储后端
生产环境组件
- Ingress:HTTP/HTTPS 路由
- Helm:包管理器
- Prometheus:监控
- Jaeger:分布式追踪
相关技术
- Docker - 容器化平台
- Gunicorn - WSGI 服务器
- Prometheus - 监控系统
- DevOps - 运维实践
录入自: Django开发实践笔记