进程管理工具——Supervisor使用技巧

用django写网站是一个很愉快的过程,这个框架是为速度而生的,有大量现成的轮子给你用,所以建站很快。然后,写完代码,我遇上了一个问题:如何把它部署到云服务器上。用过django的小伙伴都知道,django的服务是这样启动的:

$ python manage.py runsever

或者后面再加个IP和端口。

以这种方式部署到与服务器上会出现一个问题。因为我们一般都是在自己电脑上用虚拟终端登录云端的,当你执行这条命令再退出虚拟终端,进程也随之被杀死了,服务会挂掉。
怎么解决这个问题呢?一开始我使用了linux自带的nohup工具,把一个命令注册为后台进程,这样哪怕你退出云端,服务也能继续运行。但是,机器总有重启的时候吧,如果nohup开的东西太多,一旦机器重启,你能完整地记得怎么启动那些服务吗?
所以后来我找到了一个进程管理工具,编写好配置文件之后,哪怕你的机器重启,挂掉的进程也能重新启动,除非你手动把它停掉。

现在我们一起来探索一下吧。我在deepin和ubuntu下面都装了这个东西,方式是一样的

$ sudo apt-get install supervisor

然后,我们的etc下面多了个目录,我们可以直接进去看看。

$ cd  /etc/supervisor

里面一个文件夹conf.d和一个文件supervisord.conf。后者是服务器配置文件,因为supervisor本身是一个服务。我们打开这个文件看看。

$ vim supervisord.conf
; supervisor config file

[unix_http_server]
file=/var/run/supervisor.sock   ; (the path to the socket file)
chmod=0700                       ; sockef file mode (default 0700)

[supervisord]
logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log)
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
childlogdir=/var/log/supervisor            ; ('AUTO' child log dir, default $TEMP)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL  for a unix socket

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[include]
files = /etc/supervisor/conf.d/*.conf

默认是这样的,你一般不需要改什么东西,但是有个地方要注意,那就是最后一行结尾处。我这里是*.conf,但有的是*.ini。这关系到你进程文件怎么命名。好,现在我们要开始管理进程了。conf.d就是放进程文件的文件夹。看我操作。

$ cd conf.d
$ sudo vim test.conf#如果你的supervisor.donf结尾是.ini,那么你的文件名后缀也应是.ini

然后写下你要管理的进程信息,我是这么写的

[program:shop]
#执行目录
directory=/home/wufeng/code/python/project/Graduation/code/server/Shop
#启动命令
command=python3 manage.py runserver 
#自动启动
autostart=true
#自动重启
autorestart=true

然后你便可以尝试启动这个进程了。

#启动supervisor服务端
$ sudo supervisord
#启动你自己的服务,这里的supervisorctl是客户端的意思,这本来是一个C/S架构的东西
$ sudo supervisorctl start all

现在我们可以去看看我们的服务启动没

$ ps aux | grep python3
root     19494  3.0  0.5 219804 40048 ?        Sl   13:26   0:07 /usr/local/bin/python3 manage.py runserver

我设置的服务真的启动了,并且开机重启之后仍然存在。下面是一些其他操作

停止supervisor

supervisorctl shutdown

重新加载配置文件

supervisorctl reload 

启动所有进程

supervisorctl start all

停止所有进程

supervisorctl stop all

启动某个特定进程

supervisorctl start program-name

停止某个特定进程

supervisorctl stop program-name

查看当前所有进程状态

supervisorctl status

猜你喜欢

转载自blog.csdn.net/qq_42229092/article/details/104988134