使用Kubernetes部署Nginx应用教程

IDC服务

使用Kubernetes部署Nginx应用教程

2025-06-04 00:05


以下是通过 Kubernetes 部署 Nginx 应用的完整生产级方案,遵循最佳实践并适配最新 Kubernetes API(v1.28+): ? 一、部署架构核心组件

                                            




以下是通过 Kubernetes 部署 Nginx 应用的完整生产级方案,遵循最佳实践并适配最新 Kubernetes API(v1.28+):


🔧 一、部署架构核心组件

组件 作用 关键配置
Deployment 定义 Pod 副本数与更新策略 replicas: 3,rollingUpdate
ConfigMap 存储 Nginx 配置文件 支持热更新
Service 内部网络暴露服务 ClusterIP/NodePort
Ingress 外部 HTTPS 流量接入 需配合 Ingress Controller

🚀 二、逐步部署流程(使用最新 API 版本)

1️⃣ 创建 Namespace(隔离环境)

# nginx-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: web-prod

2️⃣ 定制 Nginx 配置(ConfigMap)

# nginx-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-conf
  namespace: web-prod
data:
  nginx.conf: |
    user  nginx;
    worker_processes  auto;
    error_log  /var/log/nginx/error.log warn;
    pid        /var/run/nginx.pid;
  
    events {
      worker_connections  1024;
    }
  
    http {
      include       /etc/nginx/mime.types;
      default_type  application/octet-stream;
      log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';
      access_log  /var/log/nginx/access.log  main;
      sendfile        on;
      keepalive_timeout  65;
    
      server {
        listen       80;
        server_name  localhost;
      
        location / {
          root   /usr/share/nginx/html;
          index  index.html;
        }
      
        location /health {
          return 200 'OK';
          add_header Content-Type text/plain;
        }
      }
    }

3️⃣ 创建 Deployment(带健康检查)

# nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: web-prod
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: nginx
    spec:
      securityContext:
        runAsUser: 101  # Nginx 官方镜像非 root 用户
        fsGroup: 101
      containers:
      - name: nginx
        image: nginx:1.24-alpine  # 推荐 Alpine 精简版
        ports:
        - containerPort: 80
        readinessProbe:          # 就绪探针
          httpGet:
            path: /health
            port: 80
          initialDelaySeconds: 3
          periodSeconds: 5
        livenessProbe:           # 存活探针
          httpGet:
            path: /health
            port: 80
          initialDelaySeconds: 10
          periodSeconds: 10
        volumeMounts:
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-conf

4️⃣ 暴露内部 Service

# nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
  namespace: web-prod
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: ClusterIP  # 生产环境建议 ClusterIP + Ingress

5️⃣ 部署 Ingress(外部访问)

# nginx-ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  namespace: web-prod
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx  # 需提前部署 Ingress Controller
  rules:
  - host: nginx.example.com  # 替换为真实域名
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx-svc
            port:
              number: 80

⚙️ 三、执行部署与验证

# 应用所有配置
kubectl apply -f nginx-namespace.yaml
kubectl apply -f nginx-config.yaml
kubectl apply -f nginx-deployment.yaml
kubectl apply -f nginx-service.yaml
kubectl apply -f nginx-ingress.yaml

# 检查资源状态
kubectl -n web-prod get pods -l app=nginx -w  # 观察 Pod 启动
kubectl -n web-prod describe deployment nginx # 查看部署详情
kubectl -n web-prod get service nginx-svc     # 获取 ClusterIP

# 测试内部访问
kubectl -n web-prod run curl-test --image=curlimages/curl:8.4.0 -it --rm -- \
  curl -I http://nginx-svc.web-prod.svc.cluster.local/health

# 外部访问测试 (需配置 DNS 解析)
curl -I -H "Host: nginx.example.com" http://<INGRESS_CONTROLLER_IP>

🔒 四、生产环境关键优化

  1. 配置热更新
    修改 ConfigMap 后触发 Pod 滚动更新:
    kubectl -n web-prod rollout restart deployment nginx
    
  2. HTTPS 证书配置
    通过 Cert-Manager 自动申请 Let's Encrypt 证书:
    # 在 Ingress 添加注解
    annotations:
      cert-manager.io/cluster-issuer: "letsencrypt-prod"
    spec:
      tls:
      - hosts:
        - nginx.example.com
        secretName: nginx-tls-secret
    
  3. 资源配额与 LimitRange
    防止资源过载:
    # deployment 中配置资源限制
    resources:
      limits:
        cpu: "500m"
        memory: "256Mi"
      requests:
        cpu: "100m"
        memory: "128Mi"
    
  4. 日志持久化方案
    使用 DaemonSet 收集日志到 EFK/ELK:
    # Pod 中挂载日志卷
    volumeMounts:
    - name: nginx-logs
      mountPath: /var/log/nginx
    volumes:
    - name: nginx-logs
      emptyDir: {}
    

🛡️ 五、故障排查命令速查

&
标签:
  • Kubernetes
  • Nginx
© 蓝易云.
问题类型 诊断命令
Pod 启动失败 kubectl -n web-prod describe pod <pod-name>
服务不可访问 kubectl -n web-prod get endpoints nginx-svc
配置未生效 kubectl -n web-prod exec <pod-name> -- cat /etc/nginx/nginx.conf
Ingress 路由异常