Supervisor 进程管理

概述

Supervisor 是一个 进程管理工具,将应用程序作为子进程交给它托管。它解决了生产环境两大运维痛点:

  1. 后台运行 — 自动将子进程放入后台,无需 nohup&
  2. 故障自愈 — 监控子进程状态,崩溃后自动拉起

核心功能

功能说明解决的问题
后台运行自动 daemonize 子进程替代 nohup ... &
自动重启进程崩溃时立即拉起故障自愈,减少停机时间
统一管理supervisorctl 管理所有进程替代分散的 PID 管理
日志管理自动捕获 stdout/stderr统一日志收集

架构

┌─────────────────────────────┐
│        supervisord          │  ← 守护进程(服务端)
│   (由 systemd 管理)         │
├─────────────────────────────┤
│  ┌─ program:uwsgi ───────┐  │  ← 子进程 1: Python uWSGI
│  │ uwsgi --ini uwsgi.ini  │  │
│  └────────────────────────┘  │
│  ┌─ program:chitchat ────┐  │  ← 子进程 2: Go 二进制
│  │ /go_pro/./chitchat    │  │
│  └────────────────────────┘  │
└─────────────────────────────┘
             ↕ supervisorctl
        命令行管理工具

组件说明

组件角色说明
supervisord服务端守护进程由 systemd 管理(systemctl start supervisord),负责启动/监控子进程
supervisorctl命令行客户端向 supervisord 发送管理指令(status/start/stop/restart)

安装与配置

安装

# CentOS
yum install supervisor -y
systemctl start supervisord
systemctl enable supervisord

配置文件结构

/etc/supervisord.conf          # 主配置文件(含全局配置)
/etc/supervisord.d/*.ini       # 程序配置目录(每个程序一个 .ini 文件)

程序配置示例

管理 uWSGI 服务:

# /etc/supervisord.d/uwsgi.ini
[program:uwsgi]
command=/usr/local/bin/uwsgi --ini /blog/uwsgi.ini
directory=/blog
autostart=true
autorestart=true
startretries=3
user=root
redirect_stderr=true
stdout_logfile=/var/log/supervisor/uwsgi.log

管理 Go 二进制服务:

# /etc/supervisord.d/chitchat.ini
[program:chitchat]
command=/go_pro/chitchat-master/chitchat
directory=/go_pro/chitchat-master
autostart=true
autorestart=true
startretries=3
user=root
redirect_stderr=true
stdout_logfile=/var/log/supervisor/chitchat.log

配置参数详解

参数说明
[program:xxx]程序名称,用于 supervisorctl 管理时标识
command要执行的启动命令(绝对路径)
directory执行命令前切换到此工作目录
autostart=truesupervisord 启动时自动启动该程序
autorestart=true程序异常退出后自动重启
startretries=3自动重启的最大尝试次数
user=root以哪个用户身份运行
redirect_stderr=true将 stderr 重定向到 stdout(日志统一)
stdout_logfile日志输出文件路径

管理命令

# 读取配置(添加/修改 .ini 文件后执行)
supervisorctl reread           # 检测配置文件变化
supervisorctl update           # 应用变化(启动新增/更新的程序)
 
# 进程管理
supervisorctl status           # 查看所有子进程状态
supervisorctl start uwsgi      # 启动指定程序
supervisorctl stop uwsgi       # 停止指定程序
supervisorctl restart uwsgi    # 重启指定程序
supervisorctl start all        # 启动所有程序
supervisorctl stop all         # 停止所有程序

典型工作流

# 1. 修改或新增配置
vim /etc/supervisord.d/uwsgi.ini
 
# 2. 重新加载
supervisorctl reread
supervisorctl update
 
# 3. 检查状态
supervisorctl status

适用场景

场景推荐方案原因
Python uWSGI 应用Supervisor + uWSGIuWSGI 虽有 master 进程,但本身无法自愈
Go 二进制服务Supervisor + Go 二进制Go 无内置进程管理,Supervisor 补位
多微服务同机部署Supervisor 统一管理一个 supervisorctl status 查看所有服务状态
非 Python/Go 的脚本/服务Supervisor + 任意命令任何命令行程序都可托管

补充说明:uWSGI 本身有 master 进程和 max-requests 自动重启机制,但 master 进程崩溃时 需要外部进程管理工具来拉起。Supervisor 正是填补这一层保障。


参见