Skip to content

Nginx in Kubernetes

namespace.yaml

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: common

nginx-deployment.yaml

yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: common
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.27.1
        ports:
        - containerPort: 80
        - containerPort: 443
        volumeMounts:
        - name: html-volume
          mountPath: /usr/share/nginx/html
        - name: logs-volume
          mountPath: /var/log/nginx
        - name: conf-volume
          mountPath: /etc/nginx/conf.d
        - name: nginx-conf-volume
          mountPath: /etc/nginx/nginx.conf
      restartPolicy: Always
      volumes:
      - name: html-volume
        hostPath:
          path: /root/kubernetes/common/nginx/html  # 更改为本地路径
      - name: logs-volume
        hostPath:
          path: /root/kubernetes/common/nginx/logs  # 更改为本地路径
      - name: conf-volume
        hostPath:
          path: /root/kubernetes/common/nginx/conf.d  # 更改为本地路径
      - name: nginx-conf-volume
        hostPath:
          path: /root/kubernetes/common/nginx/nginx.conf  # 更改为本地路径
          type: File
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: common
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 80
      nodePort: 80  # 在节点上暴露80端口
    - name: https    
      protocol: TCP
      port: 443
      targetPort: 443
      nodePort: 443  # 在节点上暴露443端口

Reload 脚本

reload.sh:

bash
#!/bin/bash

# 定义 Deployment 和命名空间
APP_NAME="nginx"
NAMESPACE="common"

# 获取 Deployment 下的所有 Pod 名称
PODS=$(kubectl get pods -n $NAMESPACE -l app=$APP_NAME | awk 'NR > 1 {print $1}')

for POD in $PODS; do
#  echo "Executing command on Pod: $POD"
  kubectl exec "$POD" -n "$NAMESPACE" -- nginx -s reload
done

转发流量至Kubernetes内部的Service

nginx
    location /api/yourweb/ {
        resolver kube-dns.kube-system.svc.cluster.local valid=30s;
        set $service "yourweb-service.yourwebns.svc.cluster.local";
        rewrite ^/api/yourweb(/.*)$ $1 break;
        proxy_pass http://$service$1$is_args$args;
        proxy_set_header Host $proxy_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }