从Kubernetes中的ConfigMap自定义nginx.conf



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

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

当我这样做时,当我导航到http://192.168.1.10:30008(nginx服务器运行所在节点的本地ip地址(。如果我尝试使用ConfigMap,我会收到nginx404页面/消息。

我看不出我在这里做错了什么。任何指示都将不胜感激。

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"

这是因为configmap中的location将错误的目录引用为根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;
}
}
}

最新更新