在Kubernetes中使用ConfigMap自定义nginx.conf

24
我在家庭实验室中设置了Kubernetes,并能够从部署中运行vanilla实现的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 
1个回答

18

问题很简单,就是nginx.conf中的根目录没有正确定义。

通过使用kubectl logs <<podname>> -n <<namespace>>来检查日志可以知道为什么特定请求会出现404错误

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"

这是因为您的configmap中的location将错就错地引用了目录作为根目录root html

location更改为具有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;
        }
      }
    }


1
非常感谢您指出这一点。我完全忽略了那部分内容。作为额外的奖励,您还概述了我可以获取日志文件的位置。我找不到一个很好的搜索结果来概述它们的位置。再次感谢! - Eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接