来自 Kubernetes 中 ConfigMap 的自定义 nginx.conf

Custom nginx.conf from ConfigMap in Kubernetes

我在家庭实验室中设置了 Kubernetes,我能够从部署中获得 nginx 运行 的原始实现。

下一步是为 nginx 配置创建一个自定义 nginx.conf 文件。为此,我正在使用 ConfigMap。

当我这样做时,当我导航到 http://192.168.1.10:30008 时,我不再收到 nginx 索引页面(nginx 服务器在 运行 上的节点的本地 IP 地址)。如果我尝试使用 ConfigMap,我会收到 nginx 404 page/message.

我看不出我做错了什么。任何方向将不胜感激。

nginx-deploy.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-conf
data:
  nginx.conf: |
    user nginx;
    worker_processes  1;
    events {
      worker_connections  10240;
    }
    http {
      server {
          listen       80;
          server_name  localhost;
          location / {
            root   html;
            index  index.html index.htm;
        }
      }
    }

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
        volumeMounts:
            - name: nginx-conf
              mountPath: /etc/nginx/nginx.conf
              subPath: nginx.conf
              readOnly: true
      volumes:
      - name: nginx-conf
        configMap:
          name: nginx-conf
          items:
            - key: nginx.conf
              path: nginx.conf

---
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: NodePort
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
    nodePort: 30008
  selector:
    app: nginx 

没什么复杂的,是nginx.conf中的根目录定义不正确。

使用 kubectl logs <<podname>> -n <<namespace>> 检查日志可以了解为什么 404 error 会针对特定请求发生。

xxx.xxx.xxx.xxx - - [02/Oct/2020:22:26:57 +0000] "GET / HTTP/1.1" 404 153 "-" "curl/7.58.0" 2020/10/02 22:26:57 [error] 28#28: *1 "/etc/nginx/html/index.html" is not found (2: No such file or directory), client: xxx.xxx.xxx.xxx, server: localhost, request: "GET / HTTP/1.1", host: "xxx.xxx.xxx.xxx"

这是因为 location 在您的 configmap 中引用了错误的根目录 root html

将位置更改为具有 index.html 的目录将解决此问题。这是 root /usr/share/nginx/html 的工作配置图。然而,这可以根据需要进行操作,但我们需要确保目录中存在文件。


apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-conf
data:
  nginx.conf: |
    user nginx;
    worker_processes  1;
    events {
      worker_connections  10240;
    }
    http {
      server {
          listen       80;
          server_name  localhost;
          location / {
            root   /usr/share/nginx/html; #Change this line
            index  index.html index.htm;
        }
      }
    }