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

问题描述

我在家庭实验室中设置了Kubernetes,并且能够从部署中运行Nginx的有效实现。

下一步是拥有用于配置Nginx自定义Nginx.conf文件。为此,我正在使用ConfigMap。

执行此操作时,导航到http://192.168.1.10:30008(运行Nginx服务器的节点的本地IP地址)时,我不再收到Nginx索引页面。如果尝试使用ConfigMap,则会收到Nginx 404页面/消息。

在这里我看不到我在做什么。任何方向将不胜感激。

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的有效configmap。但是,可以根据需要进行操作,但是我们需要确保目录中存在文件。


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;
        }
      }
    }