基于 CentOS 7 的 Kubernetes 资源配置实战:Deployment/Service/Ingress 配置

1. 核心概念说明
  • Deployment:管理 Pod 副本集,提供滚动更新和回滚能力
  • Service:为 Pod 提供稳定访问端点,支持负载均衡
  • Ingress:管理外部 HTTP/HTTPS 流量路由规则

2. Deployment 配置示例

功能:部署 Nginx 应用并维护 3 个副本

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3  # 副本数
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.19
        ports:
        - containerPort: 80

关键字段说明

  • replicas:Pod 副本数量
  • selector.matchLabels:绑定 Pod 标签
  • template.spec:定义容器镜像和端口

3. Service 配置示例

功能:为 Nginx Pod 创建 ClusterIP 服务

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx  # 匹配 Deployment 的标签
  ports:
    - protocol: TCP
      port: 80      # 服务端口
      targetPort: 80 # Pod 端口
  type: ClusterIP   # 默认类型

访问验证

kubectl get svc nginx-service
curl <CLUSTER-IP>:80


4. Ingress 配置示例

前提:需安装 Ingress Controller(如 Nginx Ingress)
功能:将域名 example.com 路由到 Nginx 服务

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx-service  # 关联 Service
            port:
              number: 80

关键配置

  • host:外部访问域名
  • backend.service:指向目标 Service

5. 完整部署流程
  1. 创建 Deployment

    kubectl apply -f nginx-deployment.yaml
    

  2. 创建 Service

    kubectl apply -f nginx-service.yaml
    

  3. 部署 Ingress Controller(以 Nginx Ingress 为例)

    kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml
    

  4. 创建 Ingress 规则

    kubectl apply -f nginx-ingress.yaml
    


6. 验证与调试
  • 检查资源状态
    kubectl get deployment,svc,ingress
    

  • 查看 Ingress 分配的 IP
    kubectl get ingress nginx-ingress
    

  • 本地 hosts 测试(将域名指向 Ingress IP):
    echo "<INGRESS_IP> example.com" >> /etc/hosts
    curl http://example.com
    


7. 常见问题处理
  • Pod 未启动:检查镜像拉取策略或资源限制
  • Service 无法访问:确认 selector 标签匹配
  • Ingress 404 错误:验证 Controller 日志和路由路径配置
  • CentOS 7 防火墙:确保开放 NodePort 或 LoadBalancer 端口
    firewall-cmd --add-port=30000-32767/tcp --permanent
    firewall-cmd --reload
    

提示:生产环境建议使用 HTTPS,可通过 Cert-Manager 自动管理 TLS 证书。

更多推荐