Supervisor守护Python进程

使用Python socket + HTML5 WebSocket写一个Web聊天室,上线使用时经常进程经常挂掉,然后手动重启进程,大家重新进入聊天室继续聊。时间长了以后,发现这样不是没有根本解决办法,因为每天聊天室的进程可能会因为各种原因挂掉。

Supervisor

Supervisor的出现,结束了我这苦恼的问题,它可以帮你守护任何进程,守护的意思是如果你的进程死了,会重新帮你起服务,确保你的服务一直可用。当然如果它的进程也挂了就全都over了。实际情况是上线三个多月运行非常好,没有发现服务断过。

CentOS下安装Supervisor

yum install python-setuptools
easy_install supervisor

创建配置文件

echo_supervisord_conf > /etc/supervisord.conf

在/etc/supervisord.conf末尾添加

[program:chat]
command=python /data0/htdocs/chat/main.py
priority=1
numprocs=1
autostart=true
autorestart=true

字段说明

  • command 要执行的命令
  • priority 优先级
  • numprocs 启动几个进程
  • autostart supervisor启动的时候是否随着同时启动
  • autorestart 当程序over的时候,这个program会自动重启,一定要选上

启动Supervisor

# 启动
supervisord

# 启动带配置文件
supervisord -c /etc/supervisord.conf

# 进入ctl模式
supervisorctl 

ctl中的简单命令

  • help 查看命令帮助
  • status 查看状态
  • stop <name> 停止某一个进程
  • start <name> 启动某个进程
  • restart <name> 重启某个进程
  • reload 载入最新的配置文件,停止原有进程并按新的配置启动、管理所有进程
  • update 根据最新的配置文件,启动新配置或有改动的进程,配置没有改动的进程不会受影响而重启

测试

这里以守护nginx进程来演示,首先在/etc/supervisord.conf加入

[program:nginx]
command=/usr/local/nginx/sbin/nginx
priority=1
numprocs=1
autostart=true
autorestart=true

然后启动supervisor

[root@localhost core]# supervisord -c /etc/supervisord.conf 
[root@localhost core]# ps -le | grep supervisord            
1 S     0 14035     1  0  80   0 - 48722 poll_s ?        00:00:00 supervisord

查看nginx的进程

[root@localhost core]# ps -le | grep nginx
1 S     0 14037     1  0  80   0 - 56260 rt_sig ?        00:00:00 nginx
5 S    99 14038 14037  0  80   0 - 56363 ep_pol ?        00:00:00 nginx
5 S    99 14039 14037  0  80   0 - 56300 ep_pol ?        00:00:00 nginx
5 S    99 14040 14037  0  80   0 - 56300 ep_pol ?        00:00:00 nginx

杀掉nginx进程

[root@localhost core]# kill -9 14037

然后接着重新查看nginx进程

[root@localhost core]# ps -le | grep nginx
5 S    99 14038     1  0  80   0 - 56363 ep_pol ?        00:00:00 nginx
5 S    99 14039     1  0  80   0 - 56300 ep_pol ?        00:00:00 nginx
4 S     0 14456 14035  0  80   0 - 56259 hrtime ?        00:00:00 nginx

起作用了,并且pid已经由14037变成14038。搞定!

通过web管理

supervisor可以通过web管理进程以及查看进程状态,需要在配置文件里开启

找到[inet_http_server]这一段,修改成

[inet_http_server]         ; inet (TCP) server disabled by default
port=*:9001        ; (ip_address:port specifier, *:port for all iface)
username=admin             ; (default is no username (open server))
password=123               ; (default is no password (open server))

然后保存配置,重启supervisor

supervisord reload

启用浏览器访问效果

full

注:supervisord跟Python没有任何关系,supervisord只是一个进程管理守护程序,它可以守护除Python以外的任何程序。

分享

TITLE: Supervisor守护Python进程

LINK: https://www.qttc.net/366-supervisor-daemon-process.html

NOTE: 原创内容,转载请注明出自琼台博客