You need to enable JavaScript to run this app. Kubernetes中cert-manager更新证书后Nginx挂载证书不自动生效问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes中cert-manager更新证书后Nginx挂载证书不自动生效问题咨询

问题根因是Nginx启动时会把证书内容加载到内存中,cert-manager更新Secret后,挂载到容器内的证书文件会同步更新,但Nginx不会主动重新读取文件内容,必须触发重载操作才会加载新证书,以下是两种无需重启Pod的解决方案:

方案1:新增sidecar容器监控证书变更触发重载

该方案不需要修改现有Nginx镜像,对业务侵入最小。原理是在同Pod内新增一个轻量容器,监控Secret挂载的证书目录,当检测到文件变更时自动执行nginx -s reload指令平滑重载配置,不会中断业务请求。

配置示例

  1. 在原有Deployment的containers列表下新增sidecar配置:
- name: certificate-watcher
  image: alpine:3.18
  command: ["/bin/sh", "-c"]
  args:
    - |
      apk add --no-cache inotify-tools nginx
      while true; do
        inotifywait -e modify,create,delete /etc/nginx/ssl
        nginx -s reload
        sleep 10
      done
  volumeMounts:
    - mountPath: /etc/nginx/ssl
      name: secret-volume
    - mountPath: /var/run
      name: nginx-run
  1. 在volumes下新增共享内存卷,用于sidecar和主Nginx容器通信:
volumes:
  # 原有secret-volume、configmap-volume配置保持不变
  - name: nginx-run
    emptyDir: {}
  1. 给主Nginx容器的volumeMounts新增挂载:
volumeMounts:
  # 原有ssl、conf.d挂载配置保持不变
  - mountPath: /var/run
    name: nginx-run

方案2:修改Nginx镜像内置监控逻辑

如果不想新增sidecar容器,可以把监控逻辑打包到自定义Nginx镜像中,用supervisor同时管理Nginx进程和证书监控进程。

配置示例

  1. 自定义镜像Dockerfile:
FROM nginx:1.25-alpine
RUN apk add --no-cache inotify-tools supervisor
COPY supervisord.conf /etc/supervisord.conf
COPY certificate-watch.sh /usr/local/bin/certificate-watch.sh
RUN chmod +x /usr/local/bin/certificate-watch.sh
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
  1. supervisord.conf配置:
[supervisord]
nodaemon=true
logfile=/var/log/supervisord.log
pidfile=/var/run/supervisord.pid

[program:nginx]
command=nginx -g 'daemon off;'
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:certificate-watch]
command=/usr/local/bin/certificate-watch.sh
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
  1. certificate-watch.sh脚本内容:
#!/bin/sh
while true; do
  inotifywait -e modify,create,delete /etc/nginx/ssl
  nginx -s reload
  sleep 10
done

构建镜像后替换原有Deployment中的Nginx镜像即可,不需要修改其他部署配置。

注意事项

  • Nginx的reload是平滑操作,会先启动新的工作进程处理新请求,等旧进程所有请求处理完成后再退出旧进程,不会导致业务中断
  • 可根据证书更新频率调整脚本中的sleep时间,避免短时间内多次触发重载
  • 确保监控进程和Nginx进程对证书目录有对应的读取权限

内容的提问来源于stack exchange,提问作者nightshiftman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 22:45:03