使用 supervisor 管理监控进程

By | 2018年4月22日

有时我们会在 Linux 服务器上安装运行一些非服务方式启动的程序,如 Python 程序或 nodejs 程序等,他们无法可靠的保持运行,也无法在出现错误后自动重启。这时我们就需要 Supervisor 来监控程序的运行,在意外终止时自动重启程序。

Debian 软件源已自带 Supervisor ,直接使用 apt 安装即可:apt-ge install supervisor。

安装完成后需要创建配置文件,进入 /etc/supervisor/conf.d 目录后,新建一个配置文件,如:example.conf,内容如下:

[program:ss]
command=bash /root/ssmgr.sh
autorestart=true
directory=/root
startretries=10000
user=root
redirect_stderr=true
stdout_logfile=/root/ss.log
stderr_logfile=/root/ss.log

其中,program 为程序的名称,command 为需要执行的命令,如果需要在程序退出后自动重启,设置 autostart=true 即可;directory 为程序运行目录,startretries 可以设置启动失败时的尝试次数;user 则是进程运行的用户身份。如果还需要开启日志,按照以上配置填写最后三行即可。

为了更方便的远程管理 Supervisor ,我们还可以开启其自带的 web 控制台。打开 /etc/supervisor/supervisord.conf ,在文件末尾增加以下内容:

[inet_http_server]
port=*:5000
username=user
password=123

其中,port 为监听端口,username 和 password 分别为帐号和密码。保存文件后需要重启 Supervisor:service supervisor restart,即可通过 5000 端口访问 web 控制台了。

如需通过 shell 来管理 supervisor ,可以使用以下命令:

supervisorctl start appname #启动特定程序
supervisorctl stop appname #停止特定程序
supervisorctl restart appname #重启特定程序
supervisorctl start all #启动所有程序
supervisorctl stop all #停止所有程序
supervisorctl restart all #重启所有程序

最后需要注意的是,如果使用 Supervisor 监控 shell 脚本,不能在脚本中完全使用 nohup, setsid 等后台运行命令,否则 supervisor 会误认为程序自动退出而不断重启脚本。

One thought on “使用 supervisor 管理监控进程

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

滑动到最右以进行验证 *