Kubernetes自定义Nginx配置及upstream访问应用部署问题
问题1:通过Volumes替换Nginx默认配置
Nginx官方镜像默认主配置路径为/etc/nginx/nginx.conf,通过ConfigMap存储自定义配置,再经Volume挂载覆盖目标文件即可,操作步骤如下:
- 第一步:在Nginx所在的
ingress-nginx命名空间下创建ConfigMap,写入自定义Nginx配置
apiVersion: v1 kind: ConfigMap metadata: name: custom-nginx-conf namespace: ingress-nginx data: nginx.conf: | events { worker_connections 4096; } http { upstream application_upstream { server APPLICATION_DEPLOYMENT_HOST:APPLICATION_DEPLOYMENT_PORT; } server { listen 80; location / { proxy_pass http://application_upstream; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; add_header Access-Control-Allow-Origin $http_origin; add_header Access-Control-Allow-Methods "GET,OPTIONS"; add_header Access-Control-Allow-Credentials "true"; add_header Access-Control-Allow-Headers "*"; if ($request_method = "OPTIONS") { return 200; } } } }
- 第二步:修改Nginx Deployment配置,添加Volume和挂载规则
注意必须加subPath字段指定仅覆盖nginx.conf单个文件,避免直接挂载/etc/nginx目录导致目录内其他依赖文件(如mime.types)被清空,Nginx启动失败。修改后的Deployment核心配置片段:
spec: template: spec: containers: - name: service-nginx-server image: nginx:1.7.9 ports: - containerPort: 80 # 新增配置挂载 volumeMounts: - name: nginx-conf mountPath: /etc/nginx/nginx.conf subPath: nginx.conf resources: limits: cpu: "0.4" memory: "1Gi" requests: cpu: "0.4" memory: "1Gi" # 新增Volume引用ConfigMap volumes: - name: nginx-conf configMap: name: custom-nginx-conf
配置更新部署后,新建的Nginx Pod会自动加载自定义配置。后续如果修改ConfigMap内容,需要重启Pod或在容器内执行nginx -s reload才能让新配置生效。
问题2:upstream块的地址配置
Kubernetes中Deployment管理的Pod IP会随Pod重建动态变化,不能直接填写Pod IP或Deployment名称,必须先为后端应用创建ClusterIP类型Service作为固定访问入口,再通过集群内置DNS访问Service。
操作步骤:
- 第一步:先修正后端Deployment的语法错误
你提供的后端Deployment存在字段层级、缩进错误,直接部署会失败,需要先调整:restartPolicy是Pod级字段,不属于容器配置;livenessProbe是容器字段,不需要加列表短横线;spec字段需要和metadata同级。修正后的核心片段:
apiVersion: apps/v1 kind: Deployment metadata: name: application-service namespace: namespace spec: selector: matchLabels: app: application-service template: metadata: labels: app: application-service spec: restartPolicy: OnFailure containers: - name: service-application image: some_image:latest ports: - containerPort: 8000 protocol: TCP envFrom: - secretRef: name: project-secrets livenessProbe: httpGet: path: /healthcheck/ port: 8000 protocol: HTTP resources: requests: cpu: "0.5" memory: "3Gi" limits: cpu: "0.6" memory: "3Gi"
- 第二步:为后端应用创建ClusterIP Service
在后端所在的namespace命名空间下创建Service,通过选择器关联后端Pod,暴露8000端口:
apiVersion: v1 kind: Service metadata: name: application-svc namespace: namespace spec: type: ClusterIP selector: app: application-service ports: - port: 8000 targetPort: 8000 protocol: TCP
- 第三步:填写upstream地址
由于你的Nginx部署在ingress-nginx命名空间,和后端服务不在同一命名空间,需要使用K8s全限定域名访问,upstream配置如下:
upstream application_upstream { server application-svc.namespace.svc.cluster.local:8000; }
如果后续将Nginx和后端服务部署到同一命名空间,地址可以简化为application-svc:8000。
内容的提问来源于stack exchange,提问作者CraZyCoDer
相关产品推荐
相关产品推荐

