Kubernetes 入门:部署容器集群
·
Kubernetes 入门:部署容器集群指南
1. 核心概念
- Pod:最小部署单元,包含一个或多个容器(如 Nginx + Sidecar)
- Deployment:管理 Pod 副本的声明式配置,支持滚动更新
- Service:为 Pod 提供稳定网络端点(IP + DNS)
- Cluster:由 Master 节点(控制平面)和 Worker 节点组成
2. 部署流程
步骤 1:创建 Deployment
创建 nginx-deploy.yaml 文件:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3 # 3个Pod副本
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
应用配置:
kubectl apply -f nginx-deploy.yaml
步骤 2:验证部署
kubectl get deployments # 查看Deployment状态
kubectl get pods # 检查Pod运行情况
步骤 3:创建 Service
创建 nginx-svc.yaml:
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer # 外部访问类型
启用服务:
kubectl apply -f nginx-svc.yaml
kubectl get services # 获取EXTERNAL-IP
3. 关键操作
# 扩缩容
kubectl scale deployment/nginx-deployment --replicas=5
# 更新镜像版本
kubectl set image deployment/nginx-deployment nginx=nginx:1.26
# 查看日志
kubectl logs <pod-name>
# 进入容器
kubectl exec -it <pod-name> -- /bin/bash
4. 架构示意图
用户请求
│
▼
[ Service (LoadBalancer) ]
│
├───▶ [ Pod1 (Nginx) ] ─── Node1
├───▶ [ Pod2 (Nginx) ] ─── Node2
└───▶ [ Pod3 (Nginx) ] ─── Node3
5. 最佳实践
- 资源限制:在容器配置中添加资源请求/上限
resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" - 健康检查:
livenessProbe: httpGet: path: / port: 80 - 配置分离:使用 ConfigMap 管理配置
- 存储卷:通过 PersistentVolume 持久化数据
提示:本地测试可使用 Minikube (
minikube start),生产环境推荐托管服务如 GKE/EKS/AKS。通过kubectl cluster-info验证集群状态。
更多推荐
所有评论(0)