在编写web后端的时候,我们经常会碰到有些程序需要在后台一直运行,比如异步中的消费者。因为我常用ssh连接生产服务器,所以这时在linux下通常有两种方法:
1.使用nohub命令
因为我们通过ssh连接服务器时,如果运行程序时(运行在前台),关闭ssh连接时,前台运行的程序都会停止的,所以使用nohub命令
2.使用supervisor
毕竟我们这篇文章不是主要讲命令的,还是要回到重点上来,使用supervisor可以方便的控制后台进程,让进程以daemon形式运行(守护进程)
下面是我的一个celery进程使用supervisor的配置文件:
[program:blog] command=/home/admin/venv/bin/celery -A celeryProject.app worker -l info directory=/home/admin autostart = true autorestart = true startsecs = 5 startretries = 3 user=ubuntu stderr_logfile=/home/admin/supervisor/logs/err.log stdout_logfile=/home/admin/supervisor/logs/out.log [unix_http_server] file=/tmp/supervisor.sock ;username = name ;password = password ;[inet_http_server] ;port = 0.0.0.0:5000 ;username = name ;password = password [supervisord] logfile_maxbytes=50MB logfile_backups=20 loglevel=error pidfile=/var/run/supervisord.pid nodaemon=false minfds=1024 minprocs=200 user=ubuntu [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock ;与上面[unix_http_server]部分相对应 files = /etc/supervisor/conf.d/*.conf
其中[program:blog]中是我celery的部分,因为使用了python的虚拟环境,所以celery使用的绝对路径
[supervisorctl]部分如果缺少的话,是无法使用supervisorctl来控制进程开始结束的
使用supervisorctl -c /path/to/conf/file 可以进入supervisorctl shell界面
> status #查看程序状态 > stop usercenter #关闭usercenter程序 > start usercenter > restart usercenter > reread #读取有更新的配置 > update #重启配置文件修改过的程序