如何利用 systemd 的 `DynamicUser=yes` 为每个租户启动独立的 Gunicorn 实例?

解读

面试官想确认三件事:

  1. 你是否真正理解 DynamicUser=yes 在 systemd 235+ 中的安全语义——运行时分配 UID/GID、无状态家目录、自动清理;
  2. 能否把“租户”这一业务概念映射到 独立 systemd 单元 并保证 进程、日志、监听端口、临时文件 完全隔离;
  3. 是否熟悉 Gunicorn 在 pre-fork 模型 下的 热加载、优雅重启、systemd-notify 集成,以及 Linux 网络命名空间/端口复用 等生产细节。

回答时要体现“安全隔离 + 自动化运维 + 可观测性”三板斧,避免只说“写个 service 文件”。

知识点

  • DynamicUser=yes:运行时由 systemd 动态分配 UID/GID,单元停止后自动销毁,/run、/tmp 下残留被清理,杜绝租户间 UID 冲突与残留权限。
  • Instance 单元(@.service):通过模板一次定义、无限实例化,%i 占位符对应租户 ID,实现“一行命令启停租户”。
  • RuntimeDirectory=gunicorn-%i:systemd 在 /run 下创建属主为动态用户的目录,Gunicorn 的 pid、sock、statsd 套接字均放此处,重启不丢失权限。
  • ConfigurationDirectory=gunicorn/%i:持久化租户级配置,DynamicUser 通过 ACL 自动获得 r-x,无需 chown。
  • ListenStream=%h/gunicorn.sock:每个租户独立 Unix Domain Socket,Nginx 通过 map 指令按 Host 头转发,避免端口耗尽。
  • PrivateTmp=yes / NoNewPrivileges=yes / ProtectSystem=strict:最小权限原则,即使 Python 层被 RCE,也无法越权访问宿主机或其他租户。
  • systemd-notify:Gunicorn 启动后主动通知 systemd READY=1,防止 systemd 误判启动超时。
  • KillMode=mixed:只杀主进程,worker 由 Gunicorn 自带信号优雅回收,零宕机发布。

答案

  1. 创建模板单元 /etc/systemd/system/gunicorn@.service
[Unit]
Description=Gunicorn for tenant %i
After=network.target

[Service]
Type=notify
NotifyAccess=main
DynamicUser=yes
SupplementaryGroups=nginx
RuntimeDirectory=gunicorn-%i
RuntimeDirectoryMode=0755
ConfigurationDirectory=gunicorn/%i
LogsDirectory=gunicorn/%i
LogsDirectoryMode=0755
ExecStart=/usr/local/venvs/gunicorn/bin/gunicorn \
          -c /etc/gunicorn/%i/gunicorn.conf.py \
          --bind unix:/run/gunicorn-%i/gunicorn.sock \
          --pid /run/gunicorn-%i/pid \
          --worker-tmp-dir /run/gunicorn-%i \
          --statsd-host 127.0.0.1:8125 \
          --statsd-prefix gunicorn.%i \
          'app:create_app("%i")'
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
TimeoutStopSec=30
PrivateTmp=yes
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/var/log/gunicorn/%i /run/gunicorn-%i

[Install]
WantedBy=multi-user.target
  1. 为租户 foo 准备配置
mkdir -p /etc/gunicorn/foo
cat >/etc/gunicorn/foo/gunicorn.conf.py <<'EOF'
workers = 4
worker_class = "uvicorn.workers.UvicornWorker"
max_requests = 1000
max_requests_jitter = 50
preload_app = True
access_log_format = '{"t":"%(t)s","r":"%(r)s","s":%(s)s,"T":%(T)s,"tenant":"foo"}'
accesslog = "/var/log/gunicorn/foo/access.log"
errorlog  = "/var/log/gunicorn/foo/error.log"
EOF
  1. 启动并开机自启
systemctl daemon-reload
systemctl enable --now gunicorn@foo
  1. Nginx 侧按 Host 头映射
map $host $gunicorn_sock {
    foo.example.com /run/gunicorn-foo/gunicorn.sock;
    bar.example.com /run/gunicorn-bar/gunicorn.sock;
}
server {
    listen 80;
    location / {
        proxy_pass http://unix:$gunicorn_sock:/;
    }
}
  1. 观测
systemctl status gunicorn@foo
journalctl -u gunicorn@foo -f
curl http://127.0.0.1:8125/metrics | grep gunicorn_foo

要点回顾:

  • DynamicUser 让“租户=Linux 用户”这一层完全无状态,扩容时无需提前 useradd。
  • RuntimeDirectory + LogsDirectory 解决“日志与运行时文件归属”痛点,无需 chmod 777。
  • systemd 模板 + 实例化 使运维脚本只需 systemctl start gunicorn@${tenant},CI/CD 一行指令完成租户全生命周期。

拓展思考

  1. 端口 vs Unix Socket:如果租户数量 >3 万,Unix Socket 路径长度可能超过 108 字节限制,可改用 抽象命名空间 或 IPv6 段 + SO_REUSEPORT 做 端口隔离。
  2. 热升级:利用 systemd 的 --timestamped 重启策略 与 Gunicorn 的 graceful timeout,在 Kubernetes 之外也能做到蓝绿发布。
  3. 配额:结合 systemd 的 MemoryMax/CPUQuota 与 cgroup v2,单租户可硬限制在 1 vCPU + 1 GiB,防止“邻居”耗尽节点资源。
  4. 日志审计:rsyslog 通过 $SystemdUnit 字段 把日志直接送到 Loki 或阿里云 SLS,按租户自动分索引,满足等保 2.0 审计要求。
  5. 零信任:DynamicUser 仅解决“身份隔离”,仍需 Seccomp BPF + AppArmor 做 系统调用过滤,防止 Python 调用 ptrace 提权。