在断电重启后,如何确保 Gunicorn 优先于本地 DNS 启动?

解读

国内生产环境普遍采用 systemd 作为初始化系统,DNS 解析依赖 systemd-resolved 或 NetworkManager-wait-online 这类网络服务。如果 Gunicorn 在 DNS 尚未就绪时启动,会出现 “Temporary failure in name resolution” 导致 worker 异常退出、健康检查失败 甚至 Pod 不断重启 的连锁故障。面试官想考察的是:

  1. 你是否理解 Linux 启动顺序与 systemd 单元依赖模型;
  2. 能否用最小侵入方式让 Gunicorn 等待网络层 DNS 可用,而不是傻等一个“固定时间”;
  3. 是否具备灰度、回滚、观测的闭环思维。

知识点

  1. systemd 单元依赖:After= 仅决定启动顺序,Wants=/Requires= 决定失败策略;必须同时配置。
  2. 网络就绪目标:network-online.target 由 systemd-networkd-wait-online 或 NetworkManager-wait-online 提供,保证 IP 层可达;但 DNS 层就绪 需要 nss-lookup.target。
  3. Gunicorn 的启动方式:
    • 宿主机二进制:通过 gunicorn.service 单元管理;
    • 容器化:Kubernetes 使用 initContainer 做 nslookup 探测 或 postStart 钩子;Docker 用 depends_on + condition(Compose v2 已废弃,需换 healthcheck)。
  4. 重试策略:Gunicorn 本身没有 DNS 重试,需在 ExecStartPre 里做 retry 脚本,或 systemd 的 Restart=on-failure + RestartSec=3s 限次重试。
  5. 观测手段:systemctl status gunicorn 查看 ActiveEnterTimestampMonotonic 与 network-online.target 的启动时间差;journalctl -u gunicorn -b 过滤 “Name or service not known” 关键字。

答案

宿主机方案(systemd)

  1. 创建 gunicorn.service 片段:
    [Unit]
    Description=Green Unicorn WSGI Server
    After=network-online.target nss-lookup.target
    Wants=network-online.target nss-lookup.target
    
    [Service]
    Type=notify
    ExecStartPre=/usr/bin/bash -c 'until getent hosts your-internal-domain.cn; do sleep 1; done'
    ExecStart=/usr/local/bin/gunicorn -c /etc/gunicorn.py app:application
    Restart=on-failure
    RestartSec=3
    RestartMaxDelaySec=30
    
    [Install]
    WantedBy=multi-user.target
    
  2. 启用并测试:
    systemctl daemon-reload
    systemctl enable --now gunicorn
    systemd-analyze plot | grep -E 'gunicorn|network-online'
    
  3. 断电重启验证:
    在 阿里云、腾讯云、华为云 三类机型各执行 reboot,通过 LTS 日志审计 确认 Gunicorn 首次启动时间 > nss-lookup.target 就绪时间 0.8 s 以上,且 无 worker 因 DNS 异常退出。

容器化方案(Kubernetes)

  1. initContainer 做 nslookup 探测:
    initContainers:
    - name: wait-dns
      image: busybox:1.36
      command: ['sh', '-c', 'until nslookup your-internal-domain.cn; do sleep 1; done']
    
  2. main container 的 livenessProbe 仍保留,但 initialDelaySeconds 可降到 5s,因为 DNS 已就绪。
  3. 配合 PodDisruptionBudget 与 terminationGracePeriodSeconds=35,确保 滚动重启 时旧 Pod 在 DNS 缓存失效前 优雅退出。

拓展思考

  1. 如果内网 DNS 采用 CoreDNS + NodeLocal Cache,还需等待 node-cache DaemonSet 的 readinessProbe 成功;此时 nss-lookup.target 可能提前返回,但 缓存预热 未完成,需在 initContainer 里 curl 实际业务域名 触发一次 缓存填充。
  2. 在 边缘机房 使用 4G 拨号上网,DNS 由 运营商 DHCP 下发,存在 拨号后 10~30 s 才推送 DNS 的场景;可将 systemd 单元 拆成 gunicorn-pre.service(只做 DNS 探测)与 gunicorn.service(真正拉起业务),利用 BindsTo= 实现 强依赖。
  3. 若业务对 零延迟 极端敏感,可让 Gunicorn 静态绑定 IP 绕过 DNS,但牺牲 弹性扩缩;此时需通过 Consul Template 或 CoreDNS auto-path 做 sidecar 热更新,把 DNS 变更 转化为 本地 hosts 文件 的 inotify 事件,实现 秒级生效 且 不重启 worker。