Python Flask 框架 终极部署教程,超详细。Uwsgi+Nginx+mysql+Supervisor+Virtualenv, 基于阿里云默认Linux

我发现网上还没完整详细版本的Flask 部署教程,而我在部署中遇到很多坑,所以在这里写下来,完整的教程以下是部署流程:

处理本地的代码

假设你已经完成了项目的开发,本地已经安装了git,那么首先将你的代码提交到git;

#进项目根目录
pip freeze > requirements.txt  #导flask 全部包,方便新环境下一次性安装。
git init # 之前如果没有做,那么需要做
git add --all #提交所有修改后的文件
git remote add origin http:xxxx.git  #这一步如果之前没做,那么你需要做。
git commmit -w 'first commit'

安装Mysql

现在进入服务器正式开始搭建环境,首先安装mysql.

新鲜出炉的阿里云需要更新下apt.
apt-get update
然后安装mysql, 注意一定记住root 密码,还要在配置文件中设置字符为UTF8!
增加新的数据库,注意名字和你项目的一样,
create database xxx;

安装虚拟环境 Vitualenv

pip install virtualenvwrapper #直接安装虚拟环境容器来顺便安装virtualenv
注意需要先修改环境变量。否则命名无法使用
vim ~/.bashrc   在最底部增加
#这是为了让 WORKON 命令能用。
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

然后你需要用 mkvirtualenv xxx   来创建一个叫xxx 的python 虚拟环境
workon xxx #切换到你的虚拟环境
在这个环境里,你可以升级你的python 到python3, 当然根据你的需求。

安装 Git 拿到全部源码

现在在服务器上安装git 拿到源码
apt install git
git init
git remote add origin http:xxx.git
git pull origin master # 拿到全部源码

正式部署源码

进去项目根目录:
pip install -r requirements.txt  #导入你项目的flask 依赖
pip manager.py db migerate #初始化数据库  
# 这里如果出现初始化失败,那么清空你的 migration 文件夹,你会丢掉你的测试数据,当然有不丢的办法
pip manager.py db upgrade #导入数据库,代码迁移完成

安装Nginx

apt install nginx #安装nginx 
贴下配置文件位于: /etc/nginx/conf.d/xxx.conf
# 配置nginx与uwsgi的通信方式和名称,mysite就是名称
upstream xxx {
    # nginx使用socket的方式与uwsgi进行通信
    # 这里指向你项目的目录下的socket文件,
    # 这个socket文件不需要单独创建,在运行的时候会自动创建。
    server unix:///srv/xxx/xxx.sock;
}
# 配置服务器
server {
    # 监听的端口号
    listen 80;
    # 域名或者本机的ip地址
    server_name dev.wudizu.com 47.104.22.138;
    charset     utf-8;
    # 最大的上传大小
    client_max_body_size 75M;  
    # adjust to taste

    # 访问根目录下的任何url的配置
    location / {
        # 指定访问哪个upstream
        uwsgi_pass wudi;
        # 包括uwsgi参数的文件
        include     /etc/nginx/uwsgi_params;
    }
    location /static {
        alias /srv/xxx/static;
   }

}

安装Uwsgi

pip install uwsgi

贴下配置文件:


[uwsgi]
chdir           = /srv/xxx
# 模块
module          = firstweb   #注意这里一定要你写的flask 首页文件名
# python的虚拟环境
home            = /root/.virtualenvs/flask-py2

# 是否启用mater模式
master          = true

# 进程数
processes       = 10

# socket文件地址

socket          = /srv/xxx/xxx.sock

# wsgi文件

wsgi-file       = /srv/xxx/xxx.ini

# wsgi文件中的app变量

callable        = app

# socket文件的权限

chmod-socket    = 666

安装Supervisor

sudo pip install supervisor
# supervisor的程序名字
[program:mysite]
# supervisor执行的命令
command=uwsgi --ini mysite_uwsgi.ini
# 项目的目录
directory = /srv/xxx 
# 开始的时候等待多少秒
startsecs=0
# 停止的时候等待多少秒
stopwaitsecs=0# 自动开始
autostart=true
# 程序挂了后自动重启
autorestart=true
# 输出的log文件
stdout_logfile=/srv/xxx/log/supervisord.log
# 输出的错误文件
stderr_logfile=/srv/xxx/log/supervisord.err

[supervisord]
# log的级别
loglevel=info

# 使用supervisorctl的配置
[supervisorctl]
# 使用supervisorctl登录的地址和端口号
serverurl = http://127.0.0.1:9001

# 登录supervisorctl的用户名和密码
username = admin
password = 123

[inet_http_server]
# supervisor的服务器
port = :9001
# 用户名和密码
username = admin
password = 123

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface


然后使用supervisor运行uwsgi:
supervisord -c supervisor.conf

使用supervisorctl管理supervisord:supervisor是一个C/S模型,跟redis一样,有一个服务器,也有一个客户端命令用来管理服务的,使用以下命令进入到命令界面:
supervisorctl -c supervisor.conf

指定的文件必须和supervisord服务端保持一致。 一些常用的命令有:
supervisorctl -c supervisor.conf
> status    # 查看状态
> start program_name # 启动程序
> restart program_name # 重新启动程序
> stop program_name # 停止程序
> reload # 重新加载配置文件
> quit # 退出当前的客户端

centos下安装supervisor

centos下安装supervisor

1. 安装

# yum install python-setuptools
# easy_install supervisor

成功安装后可以登陆python控制台输入import supervisor 查看是否能成功加载。

补充:如果easy_install不好使就从官方下载,然后通过python安装:

# tar zxf supervisor-xxxx.tar.gz 
# cd supervisor
# python setup.py install

2. 创建配置文件(supervisord.conf)

使用root身份创建一个全局配置文件

#echo_supervisord_conf > /etc/supervisord.conf
#supervisord -c /etc/supervisord.conf

3. 修改配置文件(supervisord.conf)

如果修改了 /etc/supervisord.conf ,需要执行 #supervisorctl reload 来重新加载配置文件,否则不会生效

supervisord 是启动supervisor 
supervisorctl 是控制supervisord

打开supervisord.conf 的 [include] 引入 files的配置.

[include] 
files = /usr/local/share/supervisor/*.conf

在supervisor建立一个你想守护的进程的文件名, redisQueue.conf

#cd  /usr/local/share/supervisor/
#vi redisQueue.conf

新增如下内容

[program:redisQueue]
command=php  /var/www/fp_dev_2/html/script/consumerQueue.php dev
user =root
autostart=true
autorestart=true
startsecs=3
stdout_logfile=/usr/local/share/supervisor/redisQueue.log
 #supervisorctl reload

说明:command=后面跟着就是你要守护的shell.

4. 运行命令

supervisorctl status
supervisorctl help

Python进程管理工具Supervisor

Linux下安装pip

wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
pip -V  #查看pip版本

Supervisor是基于Python的进程管理工具,可以更简单的监听、启停、重启服务器上的一个或多个后台进程,是Linux服务器管理的高效工具

Supervisor管理的进程,当一个进程意外被杀死,supervisort监听到进程挂掉后,会自动将它重新拉起
其进程自动恢复的功能,不再需要自己写shell脚本来控制

Supervisor 有两个主要的组成部分:

  • supervisord,运行Supervisor时会启动一个进程supervisord,它负责启动所管理的进程,并将所管理的进程作为自己的子进程来启动,而且可以在所管理的进程出现崩溃时自动重启
  • supervisorctl,是命令行管理工具,可以用来执行stop、start、restart等命令,来对这些子进程进行管理

安装setuptools

wget --no-check-certificate https://pypi.python.org/packages/source/s/setuptools/setuptools-12.0.3.tar.gz#md5=f07e4b0f4c1c9368fcd980d888b29a65
tar -zxvf setuptools-12.0.3.tar.gz
cd setuptools-12.0.3
python setup.py install

安装pip

easy_install pip

安装supervisor

easy_install supervisor

测试是否安装成功

echo_supervisord_conf

创建配置文件

echo_supervisord_conf > /etc/supervisord.conf

如果出现没有权限的问题,可以使用这条命令

sudo su - root -c "echo_supervisord_conf > /etc/supervisord.conf"

supervisor安装完成后会生成三个执行程序:

* supervisortd【supervisor的守护进程服务(用于接收进程管理命令)】 
* supervisorctl【客户端(用于和守护进程通信,发送管理进程的指令)】 
* echo_supervisord_conf【生成初始配置文件程序】

配置文件说明

想要了解怎么配置需要管理的进程,只要打开 supervisord.conf 就可以了,里面有很详细的注释信息

打开配置文件

vim /etc/supervisord.conf

默认的配置文件是下面这样的,但是这里有个坑需要注意,supervisord.pid 以及 supervisor.sock 是放在 /tmp 目录下

但是 /tmp 目录是存放临时文件,里面的文件是会被 Linux 系统删除的

一旦这些文件丢失,就无法再通过 supervisorctl 来执行 restart 和 stop 命令了,

将只会得到 unix:///tmp/supervisor.sock 不存在的错误
因此可以单独建一个文件夹,来存放这些文件,比如放在 /etc/supervisord.d/
默认情况下,进程的日志文件达到50MB时,将进行分割,最多保留10个文件,当然这些配置也可以对每个进程单独配置

创建文件夹

mkdir -p /etc/supervisord.d

创建日志目录

mkdir -p /var/log/supervisor/
supervisord.conf
; Sample supervisor config file.
;
; For more information on the config file, please see:
; http://supervisord.org/configuration.html
;
; Notes:
;  - Shell expansion ("~" or "$HOME") is not supported.  Environment
;    variables can be expanded using this syntax: "%(ENV_HOME)s".
;  - Quotes around values are not supported, except in the case of
;    the environment= options as shown below.
;  - Comments must have a leading space: "a=b ;comment" not "a=b;comment".
;  - Command will be truncated if it looks like a config file comment, e.g.
;    "command=bash -c 'foo ; bar'" will truncate to "command=bash -c 'foo ".

[unix_http_server]
; 修改为/etc/supervisord.d目录,避免被系统删除
file=/etc/supervisord.d/supervisor.sock   ; the path to the socket file
;chmod=0700                 ; socket file mode (default 0700)
;chown=nobody:nogroup       ; socket file uid:gid owner
;username=user              ; default is no username (open server)
;password=123               ; default is no password (open server)

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

[supervisord]
; logfile=/tmp/supervisord.log ; main log file; default $CWD/supervisord.log
; 修改为 /var/log 目录,避免被系统删除
logfile=/var/log/supervisor/supervisord.log ;
; 日志文件多大时进行分割
logfile_maxbytes=50MB        ; max main logfile bytes b4 rotation; default 50MB
; 最多保留多少份日志文件
logfile_backups=10           ; # of main logfile backups; 0 means none, default 10
loglevel=info                ; log level; default info; others: debug,warn,trace
; 修改为/etc/supervisord.d目录,避免被系统删除
pidfile=/etc/supervisord.d/supervisord.pid ; supervisord pidfile; default supervisord.pid
nodaemon=false               ; start in foreground if true; default false
minfds=1024                  ; min. avail startup file descriptors; default 1024
minprocs=200                 ; min. avail process descriptors;default 200
;umask=022                   ; process file creation umask; default 022
; 设置启动supervisord的用户,一般情况下不要轻易用root用户来启动,除非你真的确定要这么做
user=root                 ; default is current user, required if root
;identifier=supervisor       ; supervisord identifier, default is 'supervisor'
;directory=/tmp              ; default is not to cd during start
;nocleanup=true              ; don't clean up tempfiles at start; default false
;childlogdir=/tmp            ; 'AUTO' child log dir, default $TEMP
;environment=KEY="value"     ; key value pairs to add to environment
;strip_ansi=false            ; strip ansi escape codes in logs; def. false

; The rpcinterface:supervisor 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:x] sections.

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

; The supervisorctl section configures how supervisorctl will connect to
; supervisord.  configure it match the settings in either the unix_http_server
; or inet_http_server section.

[supervisorctl]
; 必须和'unix_http_server'里面的设定匹配
; 修改为/etc/supervisor目录,避免被系统删除
;serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL  for a unix socket
serverurl=unix:///etc/supervisord.d/supervisor.sock ;
;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket
;username=chris              ; should be same as in [*_http_server] if set
;password=123                ; should be same as in [*_http_server] if set
;prompt=mysupervisor         ; cmd line prompt (default "supervisor")
;history_file=~/.sc_history  ; use readline history if available

; The sample program section below shows all possible program subsection values.
; Create one or more 'real' program: sections to be able to control them under
; supervisor.

;[program:theprogramname]
;command=/bin/cat              ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1                    ; number of processes copies to start (def 1)
;directory=/tmp                ; directory to cwd to before exec (def no cwd)
;umask=022                     ; umask for process (default None)
;priority=999                  ; the relative start priority (default 999)
;autostart=true                ; start at supervisord start (default: true)
;startsecs=1                   ; # of secs prog must stay up to be running (def. 1)
;startretries=3                ; max # of serial start failures when starting (default 3)
;autorestart=unexpected        ; when to restart if exited after running (def: unexpected)
;exitcodes=0,2                 ; 'expected' exit codes used with autorestart (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false             ; send stop signal to the UNIX process group (default false)
;killasgroup=false             ; SIGKILL the UNIX process group (def false)
;user=chrism                   ; setuid to this UNIX account to run the program
;redirect_stderr=true          ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path        ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10     ; # of stdout logfile backups (0 means none, default 10)
;stdout_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stdout_events_enabled=false   ; emit events on stdout writes (default false)
;stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10     ; # of stderr logfile backups (0 means none, default 10)
;stderr_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stderr_events_enabled=false   ; emit events on stderr writes (default false)
;environment=A="1",B="2"       ; process environment additions (def no adds)
;serverurl=AUTO                ; override serverurl computation (childutils)

; The sample eventlistener section below shows all possible eventlistener
; subsection values.  Create one or more 'real' eventlistener: sections to be
; able to handle event notifications sent by supervisord.

;[eventlistener:theeventlistenername]
;command=/bin/eventlistener    ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1                    ; number of processes copies to start (def 1)
;events=EVENT                  ; event notif. types to subscribe to (req'd)
;buffer_size=10                ; event buffer queue size (default 10)
;directory=/tmp                ; directory to cwd to before exec (def no cwd)
;umask=022                     ; umask for process (default None)
;priority=-1                   ; the relative start priority (default -1)
;autostart=true                ; start at supervisord start (default: true)
;startsecs=1                   ; # of secs prog must stay up to be running (def. 1)
;startretries=3                ; max # of serial start failures when starting (default 3)
;autorestart=unexpected        ; autorestart if exited after running (def: unexpected)
;exitcodes=0,2                 ; 'expected' exit codes used with autorestart (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false             ; send stop signal to the UNIX process group (default false)
;killasgroup=false             ; SIGKILL the UNIX process group (def false)
;user=chrism                   ; setuid to this UNIX account to run the program
;redirect_stderr=false         ; redirect_stderr=true is not allowed for eventlisteners
;stdout_logfile=/a/path        ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10     ; # of stdout logfile backups (0 means none, default 10)
;stdout_events_enabled=false   ; emit events on stdout writes (default false)
;stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10     ; # of stderr logfile backups (0 means none, default 10)
;stderr_events_enabled=false   ; emit events on stderr writes (default false)
;environment=A="1",B="2"       ; process environment additions
;serverurl=AUTO                ; override serverurl computation (childutils)

; The sample group section below shows all possible group values.  Create one
; or more 'real' group: sections to create "heterogeneous" process groups.

;[group:thegroupname]
;programs=progname1,progname2  ; each refers to 'x' in [program:x] definitions
;priority=999                  ; the relative start priority (default 999)

; 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/supervisord.d/config/*.ini

使用include

在配置文件的最后,有一个 [include] 的配置项,跟 Nginx 一样,可以 include 某个文件夹下的所有配置文件,这样我们就可以为每个进程或相关的几个进程的配置单独写成一个文件

[include]
files = /etc/supervisord.d/config/*.ini

创建进程的配置文件

编辑/etc/supervisord.d/config/matrix.ini

[group:matrix]
programs = matrix.print

[program:matrix.print]
; 启动命令,可以看出与手动在命令行启动的命令是一样的
command=python /data/demo/demo.py
numprocs=1
numprocs_start=0
priority=999
; 在supervisord启动的时候也自动启动
autostart=true
; 启动3秒后没有异常退出,就当作已经正常启动了
startsecs=3
; 启动失败自动重试次数,默认是3
startretries=3
exitcodes=0,2
stopsignal=QUIT
stopwaitsecs=60
directory=/data/demo
user=root
; 默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程
stopasgroup=false
; 默认为false,向进程组发送kill信号,包括子进程
killasgroup=false
redirect_stderr=true
;stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile=/data/demo/data.log
; 日志文件多大时进行分割
stdout_logfile_maxbytes=250MB
; 最多保留多少份日志文件
stdout_logfile_backups=10
stderr_logfile=/data/demo/data.err
stderr_logfile_maxbytes=250MB
stderr_logfile_backups=10
; 可以通过 environment 来添加需要的环境变量,一种常见的用法是修改 PYTHONPATH
environment=PYTHONPATH="/data/demo"

创建测试脚本&日志目录

mkdir -p /data/demo

/data/demo/demo.py

vi /data/demo/demo.py
# -*- coding: utf-8 -*-
import os
import time

while 1:
   f = open('data.log', 'a+')
   time.sleep(5)
   f.write('This is a Test!')

启动supervisor

supervisord -c /etc/supervisord.conf

查看supervisor是否启动成功

ps -ef | grep '/etc/supervisord.conf'
root     23542     1  0 17:46 ?        00:00:00 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf
root     23566 23079  0 17:54 pts/0    00:00:00 grep /etc/supervisord.conf

查看supervisord.log

tail -f /var/log/supervisor/supervisord.log
2017-10-31 17:46:18,672 CRIT Set uid to user 0
2017-10-31 17:46:18,678 INFO RPC interface 'supervisor' initialized
2017-10-31 17:46:18,678 CRIT Server 'unix_http_server' running without any HTTP authentication checking
2017-10-31 17:46:18,679 INFO daemonizing the supervisord process
2017-10-31 17:46:18,679 INFO supervisord started with pid 23542
2017-10-31 17:48:14,042 INFO spawned: 'matrix.print' with pid 23555
2017-10-31 17:48:17,047 INFO success: matrix.print entered RUNNING state, process has stayed up for > than 3 seconds (startsecs)

supervisord.conf配置文件参数说明

[unix_http_server]
file=/tmp/supervisor.sock   ;UNIX socket 文件,supervisorctl 会使用
;chmod=0700                 ;socket文件的mode,默认是0700
;chown=nobody:nogroup       ;socket文件的owner,格式:uid:gid

;[inet_http_server]         ;HTTP服务器,提供web管理界面
;port=127.0.0.1:9001        ;Web管理后台运行的IP和端口,如果开放到公网,需要注意安全性
;username=user              ;登录管理后台的用户名
;password=123               ;登录管理后台的密码

[supervisord]
logfile=/tmp/supervisord.log ;日志文件,默认是 $CWD/supervisord.log
logfile_maxbytes=50MB        ;日志文件大小,超出会rotate,默认 50MB,如果设成0,表示不限制大小
logfile_backups=10           ;日志文件保留备份数量默认10,设为0表示不备份
loglevel=info                ;日志级别,默认info,其它: debug,warn,trace
pidfile=/tmp/supervisord.pid ;pid 文件
nodaemon=false               ;是否在前台启动,默认是false,即以 daemon 的方式启动
minfds=1024                  ;可以打开的文件描述符的最小值,默认 1024
minprocs=200                 ;可以打开的进程数的最小值,默认 200

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ;通过UNIX socket连接supervisord,路径与unix_http_server部分的file一致
;serverurl=http://127.0.0.1:9001 ; 通过HTTP的方式连接supervisord

; [program:xx]是被管理的进程配置参数,xx是进程的名称
[program:xx]
command=/opt/apache-tomcat-8.0.35/bin/catalina.sh run  ; 程序启动命令
autostart=true       ; 在supervisord启动的时候也自动启动
startsecs=10         ; 启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒
autorestart=true     ; 程序退出后自动重启,可选值:[unexpected,true,false],默认为unexpected,表示进程意外杀死后才重启
startretries=3       ; 启动失败自动重试次数,默认是3
user=tomcat          ; 用哪个用户启动进程,默认是root
priority=999         ; 进程启动优先级,默认999,值小的优先启动
redirect_stderr=true ; 把stderr重定向到stdout,默认false
stdout_logfile_maxbytes=20MB  ; stdout 日志文件大小,默认50MB
stdout_logfile_backups = 20   ; stdout 日志文件备份数,默认是10
; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out
stopasgroup=false     ;默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程
killasgroup=false     ;默认为false,向进程组发送kill信号,包括子进程

;包含其它配置文件
[include]
files = relative/directory/*.ini    ;可以指定一个或多个以.ini结束的配置文件

supervisorctl命令介绍

# 停止某一个进程,program_name 为 [program:x] 里的 x
supervisorctl stop program_name
# 启动某个进程
supervisorctl start program_name
# 重启某个进程
supervisorctl restart program_name
# 结束所有属于名为 groupworker 这个分组的进程 (start,restart 同理)
supervisorctl stop groupworker:
# 结束 groupworker:name1 这个进程 (start,restart 同理)
supervisorctl stop groupworker:name1
# 停止全部进程,注:start、restart、stop 都不会载入最新的配置文件
supervisorctl stop all
# 载入最新的配置文件,停止原有进程并按新的配置启动、管理所有进程
supervisorctl reload
# 根据最新的配置文件,启动新配置或有改动的进程,配置没有改动的进程不会受影响而重启
supervisorctl update
# 查看进程的状态
supervisorctl status

查看进程状态

supervisorctl status
matrix:matrix.print              RUNNING   pid 23555, uptime 0:10:00

查看supervisord所在路径

which supervisord

使用浏览器来管理

supervisor 同时提供了通过浏览器来管理进程的方法,只需要注释掉如下几行就可以了
;[inet_http_server]         ; inet (TCP) server disabled by default
;port=192.168.3.244:9001        ; (ip_address:port specifier, *:port for ;all iface)
;username=user              ; (default is no username (open server))
;password=123               ; (default is no password (open server))
[supervisorctl]
...
;serverurl=http://192.168.3.244:9001 ; use an http:// url to specify an inet socket
;username=chris              ; should be same as http_username if set
;password=123                ; should be same as http_password if set

访问浏览器地址栏:http://192.168.3.244:9001/

未分类

开机自动启动Supervisord

Linux在启动的时候会执行/etc/rc.local里面的脚本,所以在这里添加执行命令就可以

# 如果是 Ubuntu 添加以下内容
/usr/local/bin/supervisord -c /etc/supervisord.conf
# 如果是 Centos 添加以下内容
/usr/bin/supervisord -c /etc/supervisord.conf

启用rc.local服务

sudo systemctl enable rc-local.service

Supervisor进程监视管理

supervisor是用Python开发的一套通用的进程管理程序,可以将一个普通的命令行进程变为后台daemon,并监控进程状态,异常退出时可以自动重启。

安装Supervisor

# yum search setuptools
....
python-setuptools.noarch : Easily build and distribute Python packages
#yum install -y python-setuptools.noarch
#easy_install supervisor

创建主配置文件

# mkdir -m 755 -p /etc/supervisor          \创建supervisor配置文件目录
# echo_supervisord_conf >/etc/supervisor/supervisord.conf    \创建主配置文件
# cd /etc/supervisor/
# mkdir -m 755 conf.d             \创建项目配置文件目录

创建项目配置文件(运行3个脚本)

# vim conf.d/test.ini
[program:tjapp_sendmessage]
command=/bin/bash /data/shell/sendmessage.sh
numprocs=1
autostart=true
autorestart=true

[program:bbscollection]
command=/bin/bash /data/shell/bbscollection.sh
numprocs=1
autostart=true
autorestart=true

[program:test_sbbscollection]
command=/bin/bash /data/shell/test_sbbscollection.sh
numprocs=1
autostart=true
autorestart=true

在主配置文件中引入test.ini

#cat supervisord.conf
...
[include]
files = ./conf.d/*.ini

启动supervisor

# supervisord -c /etc/supervisor/supervisord.conf

查看supervisor运行的脚本

# supervisorctl
bbscollection                    RUNNING   pid 10090, uptime 4 days, 17:20:10
test_sbbscollection              RUNNING   pid 10088, uptime 4 days, 17:20:10
tjapp_sendmessage                RUNNING   pid 10089, uptime 4 days, 17:20:10

停止bbscollection脚本

# supervisorctl stop bbscollection
bbscollection: stopped

# supervisorctl
bbscollection                    STOPPED   Apr 06 10:23 AM
test_sbbscollection              RUNNING   pid 10088, uptime 4 days, 17:23:13
tjapp_sendmessage                RUNNING   pid 10089, uptime 4 days, 17:23:13

# supervisor> start bbscollection  \启动

# supervisor> status
bbscollection                    RUNNING   pid 7310, uptime 0:00:24
test_sbbscollection              RUNNING   pid 10088, uptime 4 days, 17:23:54
tjapp_sendmessage                RUNNING   pid 10089, uptime 4 days, 17:23:54

systemctl管理

vim /usr/lib/systemd/system/supervisord.service
# supervisord service for sysstemd (CentOS 7.0+)
# by ET-CS (https://github.com/ET-CS)
[Unit]
Description=Supervisor daemon
[Service]
Type=forking
ExecStart=/usr/bin/supervisord
ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown
ExecReload=/usr/bin/supervisorctl $OPTIONS reload
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
#systemctl enable supervisord.service

用supervisor+nginx部署服务的流程

以chat_service为例:

1、将项目拷贝至某一路径

2、更改supervisor配置文件:supervisor.conf(一般在/etc/目录下)

  • 在/etc/supervisor.d/目录下新建chat_service.conf配置文件,如下:
[program:chat_service]
command=/usr/local/bin/gunicorn -b 0.0.0.0:8001 -w 40 -k gevent -t 300 chat_service.wsgi:application
directory=/home/hongkeyuan/chat/bin/chat_system/chat_service
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/home/hongkeyuan/chat/log/chat_service.log
stderr_logfile=/home/hongkeyuan/chat/log/chat_service.err
  • 将配置文件包含到supervisor.conf中,在supervisor.conf中加入:
[include]
files = /etc/supervisor.d/*.conf

3、更改nginx配置文件,/etc/nginx/conf.d/目录下新建chat_service.conf配置文件,如下:

upstream chat_service {
        server localhost:8001;
}

server {
        listen 8000;
        location /static {
                alias /home/robot/chat/bin/chat_system/chat_service/static;
        }
        location / {
                proxy_pass_header Server;
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Scheme $scheme;
                proxy_pass http://chat_service;
        }
}

4、重新加载supervisor:supervisorctl -c /etc/supervisor.conf reload,此时配置的服务也将重启。

5、重新加载nginx:nginx -s reload。

tips:

  • 如果需要sudo权限,相关命令前需要加sudo。
  • 这里nginx主要起重定向作用,如果不需要重定向,则无需配置nginx。

Supervisor安装与配置(Linux/Unix进程管理工具)

Supervisor(http://supervisord.org/)是用Python开发的一个client/server服务,是Linux/Unix系统下的一个进程管理工具,不支持Windows系统。它可以很方便的监听、启动、停止、重启一个或多个进程。用Supervisor管理的进程,当一个进程意外被杀死,supervisort监听到进程死后,会自动将它重新拉起,很方便的做到进程自动恢复的功能,不再需要自己写shell脚本来控制。

因为Supervisor是Python开发的,安装前先检查一下系统否安装了Python2.4以上版本。下面以CentOS7,Python2.7版本环境下,介绍Supervisor的安装与配置步聚:

一、安装Python包管理工具(easy_install)

easy_install是setuptools包里带的一个命令,使用easy_install实际上是在调用setuptools来完成安装模块的工作,所以安装setuptools即可。

wget --no-check-certificate https://bootstrap.pypa.io/ez_setup.py -O - | sudo python

二、安装supervisor

easy_install supervisor

supervisor安装完成后会生成三个执行程序:supervisortd、supervisorctl、echo_supervisord_conf,分别是supervisor的守护进程服务(用于接收进程管理命令)、客户端(用于和守护进程通信,发送管理进程的指令)、生成初始配置文件程序。

三、配置

运行supervisord服务的时候,需要指定supervisor配置文件,如果没有显示指定,默认在以下目录查找:

$CWD/supervisord.conf
$CWD/etc/supervisord.conf
/etc/supervisord.conf
/etc/supervisor/supervisord.conf (since Supervisor 3.3.0)
../etc/supervisord.conf (Relative to the executable)
../supervisord.conf (Relative to the executable)

$CWD表示运行supervisord程序的目录。

可以通过运行echo_supervisord_conf程序生成supervisor的初始化配置文件,如下所示:

mkdir /etc/supervisor
echo_supervisord_conf > /etc/supervisor/supervisord.conf

四、配置文件参数说明

supervisor的配置参数较多,下面介绍一下常用的参数配置,详细的配置及说明,请参考官方文档介绍。

注:分号(;)开头的配置表示注释

[unix_http_server]
file=/tmp/supervisor.sock   ;UNIX socket 文件,supervisorctl 会使用
;chmod=0700                 ;socket文件的mode,默认是0700
;chown=nobody:nogroup       ;socket文件的owner,格式:uid:gid

;[inet_http_server]         ;HTTP服务器,提供web管理界面
;port=127.0.0.1:9001        ;Web管理后台运行的IP和端口,如果开放到公网,需要注意安全性
;username=user              ;登录管理后台的用户名
;password=123               ;登录管理后台的密码

[supervisord]
logfile=/tmp/supervisord.log ;日志文件,默认是 $CWD/supervisord.log
logfile_maxbytes=50MB        ;日志文件大小,超出会rotate,默认 50MB,如果设成0,表示不限制大小
logfile_backups=10           ;日志文件保留备份数量默认10,设为0表示不备份
loglevel=info                ;日志级别,默认info,其它: debug,warn,trace
pidfile=/tmp/supervisord.pid ;pid 文件
nodaemon=false               ;是否在前台启动,默认是false,即以 daemon 的方式启动
minfds=1024                  ;可以打开的文件描述符的最小值,默认 1024
minprocs=200                 ;可以打开的进程数的最小值,默认 200

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ;通过UNIX socket连接supervisord,路径与unix_http_server部分的file一致
;serverurl=http://127.0.0.1:9001 ; 通过HTTP的方式连接supervisord

; [program:xx]是被管理的进程配置参数,xx是进程的名称
[program:xx]
command=/opt/apache-tomcat-8.0.35/bin/catalina.sh run  ; 程序启动命令
autostart=true       ; 在supervisord启动的时候也自动启动
startsecs=10         ; 启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒
autorestart=true     ; 程序退出后自动重启,可选值:[unexpected,true,false],默认为unexpected,表示进程意外杀死后才重启
startretries=3       ; 启动失败自动重试次数,默认是3
user=tomcat          ; 用哪个用户启动进程,默认是root
priority=999         ; 进程启动优先级,默认999,值小的优先启动
redirect_stderr=true ; 把stderr重定向到stdout,默认false
stdout_logfile_maxbytes=20MB  ; stdout 日志文件大小,默认50MB
stdout_logfile_backups = 20   ; stdout 日志文件备份数,默认是10
; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out
stopasgroup=false     ;默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程
killasgroup=false     ;默认为false,向进程组发送kill信号,包括子进程

;包含其它配置文件
[include]
files = relative/directory/*.ini    ;可以指定一个或多个以.ini结束的配置文件

include示例:

[include]
files = /opt/absolute/filename.ini /opt/absolute/*.ini foo.conf config??.ini

五、配置管理进程

进程管理配置参数,不建议全都写在supervisord.conf文件中,应该每个进程写一个配置文件放在include指定的目录下包含进supervisord.conf文件中。

1> 创建/etc/supervisor/config.d目录,用于存放进程管理的配置文件
2> 修改/etc/supervisor/supervisord.conf中的include参数,将/etc/supervisor/conf.d目录添加到include中

[include]
files = /etc/supervisor/config.d/*.ini

未分类

supervisor配置文件目录结构

下面是配置Tomcat进程的一个例子:

[program:tomcat]
command=/opt/apache-tomcat-8.0.35/bin/catalina.sh run
stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out
autostart=true
autorestart=true
startsecs=5
priority=1
stopasgroup=true
killasgroup=true

六、启动Supervisor服务

supervisord -c /etc/supervisor/supervisord.conf

七、控制进程

7.1 交互终端

supervisord启动成功后,可以通过supervisorctl客户端控制进程,启动、停止、重启。运行supervisorctl命令,不加参数,会进入supervisor客户端的交互终端,并会列出当前所管理的所有进程。

未分类

上图中的tomcat就是我们在配置文件中[program:tomcat]指定的名字。
输入help可以查看可以执行的命令列表,如果想看某个命令的作用,运行help 命令名称,如:help stop

stop tomcat  // 表示停止tomcat进程
stop all     // 表示停止所有进程
// ...

7.2 bash终端

supervisorctl status
supervisorctl stop tomcat
supervisorctl start tomcat
supervisorctl restart tomcat
supervisorctl reread
supervisorctl update

7.3 Web管理界面

未分类

出于安全考虑,默认配置是没有开启web管理界面,需要修改supervisord.conf配置文件打开http访权限,将下面的配置:

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

修改成:

[inet_http_server]         ; inet (TCP) server disabled by default
port=0.0.0.0:9001          ; (ip_address:port specifier, *:port for all iface)
username=user              ; (default is no username (open server))
password=123               ; (default is no password (open server))
  • port:绑定访问IP和端口,这里是绑定的是本地IP和9001端口
  • username:登录管理后台的用户名
  • password:登录管理后台的密码

八、开机启动Supervisor服务

8.1 配置systemctl服务

1> 进入/lib/systemd/system目录,并创建supervisor.service文件

[Unit]
Description=supervisor
After=network.target

[Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisor/supervisord.conf
ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown
ExecReload=/usr/bin/supervisorctl $OPTIONS reload
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

2> 设置开机启动

systemctl enable supervisor.service
systemctl daemon-reload

3> 修改文件权限为766

chmod 766 supervisor.service

8.2 配置service类型服务

#!/bin/bash
#
# supervisord   This scripts turns supervisord on
#
# Author:       Mike McGrath <[email protected]> (based off yumupdatesd)
#
# chkconfig:    - 95 04
#
# description:  supervisor is a process control utility.  It has a web based
#               xmlrpc interface as well as a few other nifty features.
# processname:  supervisord
# config: /etc/supervisor/supervisord.conf
# pidfile: /var/run/supervisord.pid
#

# source function library
. /etc/rc.d/init.d/functions

RETVAL=0

start() {
    echo -n $"Starting supervisord: "
    daemon "supervisord -c /etc/supervisor/supervisord.conf "
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/supervisord
}

stop() {
    echo -n $"Stopping supervisord: "
    killproc supervisord
    echo
    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/supervisord
}

restart() {
    stop
    start
}

case "$1" in
  start)
    start
    ;;
  stop) 
    stop
    ;;
  restart|force-reload|reload)
    restart
    ;;
  condrestart)
    [ -f /var/lock/subsys/supervisord ] && restart
    ;;
  status)
    status supervisord
    RETVAL=$?
    ;;
  *)
    echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart}"
    exit 1
esac

exit $RETVAL

将上述脚本内容保存到/etc/rc.d/init.d/supervisor文件中,修改文件权限为755,并设置开机启动

chmod 755 /etc/rc.d/init.d/supervisor
chkconfig supervisor on

注意:修改脚本中supervisor配置文件路径为你的supervisor的配置文件路径

其它Linux发行版开机启动脚本:https://github.com/Supervisor/initscripts

注意:

Supervisor只能管理非daemon的进程,也就是说Supervisor不能管理守护进程。否则提示Exited too quickly (process log may have details)异常。例子中的Tomcat默认是以守护进程启动的,所以我们改成了catalina.sh run,以前台进程的方式运行。

yum方式安装

yum install epel-release
yum install -y supervisor

supervisor没有发布在标准的CentOS源在,需要安装epel源。这种方式安装的可能不是最新版本,但比较方便,安装完成之后,配置文件会自动帮你生成。

默认配置文件:/etc/supervisord.conf
进程管理配置文件放到:/etc/supervisord.d/目录下即可

默认日志文件:/tmp/supervisord.log,可以查看进程的启动信息

laravel 守护进程Supervisor的配置

安装Supervisor

Supervisor是Linux系统中常用的进程守护程序。如果队列进程queue:work意外关闭,它会自动重启启动队列进程。在Ubuntu安装Supervisor 非常简单:

sudo apt-get install supervisor

注:如果自己配置Supervisor有困难,可以考虑使用Laravel Forge,它会为Laravel项目自动安装并配置Supervisor。

配置Supervisor

Supervisor配置文件通常存放在/etc/supervisor/conf.d目录,在该目录中,可以创建多个配置文件指示Supervisor如何监视进程,例如,让我们创建一个开启并监视queue:work进程的laravel-worker.conf文件:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3
autostart=true
autorestart=true
user=forge
numprocs=8
redirect_stderr=true
stdout_logfile=/home/forge/app.com/worker.log

在本例中,numprocs指令让Supervisor运行8个queue:work进程并监视它们,如果失败的话自动重启。配置文件创建好了之后,可以使用如下命令更新Supervisor配置并开启进程:

启动Supervisor

当你成功创建配置文件后,你需要刷新Supervisor 的配置信息:

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*

你可以通过Supervisor官方文档获的更多信息: http://supervisord.org/index.html

进程管理利器-supervisor部署记录

一、简单介绍

supervisor是用来管理进程的一个工具,止于为什么要用supervisor,是因为相对于linux传统的进程管理方式来说,它有很多的优势:

----简单----
通常管理linux进程的时候,一般来说都需要自己编写一个能够实现进程start/stop/restart/reload功能的脚本,然后丢到/etc/init.d/下面。这么做有很多不好的地方,第一我们要编写这个脚本,这就很耗时耗力了。
第二,当这个进程挂掉的时候,linux不会自动重启它的,想要自动重启的话,我们还要自己写一个监控重启脚本。而,supervisor则可以完美的解决这些问题。好,怎么解决的呢,其实supervisor管理进程,就是通过
fork/exec的方式把这些被管理的进程,当作supervisor的子进程来启动。这样的话,我们只要在supervisor的配置文件中,把要管理的进程的可执行文件的路径写进去就OK了。这样就省下了我们如同linux管理进程的时候,
自己写控制脚本的麻烦了。第二,被管理进程作为supervisor的子进程,当子进程挂掉的时候,父进程可以准确获取子进程挂掉的信息的,所以当然也就可以对挂掉的子进程进行自动重启了,当然重启还是不重启,也要看你的
配置文件里面有木有设置autostart=true了,这是后话。

----精确----
为啥说精确呢?因为linux对进程状态的反馈,有时候不太准确。为啥不准确?这个楼主也不知道啊,官方文档是这么说的,知道的告诉楼主一下吧,感激不尽。而supervisor监控子进程,得到的子进程状态无疑是准确的。
进程组supervisor可以对进程组统一管理,也就是说咱们可以把需要管理的进程写到一个组里面,然后我们把这个组作为一个对象进行管理,如启动,停止,重启等等操作。而linux系统则是没有这种功能的,我们想要停止
一个进程,只能一个一个的去停止,要么就自己写个脚本去批量停止。

-----集中式管理-----
supervisor管理的进程,进程组信息,全部都写在一个ini格式的文件里就OK了。而且,我们管理supervisor的时候的可以在本地进行管理,也可以远程管理,而且supervisor提供了一个web界面,我们可以在web界面上监控,
管理进程。 当然了,本地,远程和web管理的时候,需要调用supervisor的xml_rpc接口,这个也是后话。

---有效性----
当supervisor的子进程挂掉的时候,操作系统会直接给supervisor发信号。而其他的一些类似supervisor的工具,则是通过进程的pid文件,来发送信号的,然后定期轮询来重启失败的进程。显然supervisor更加高效。。。
至于是哪些类似supervisor工具,这个楼主就不太清楚了,楼主还听说过god,director,但是没用过。有兴趣的朋友可以玩玩

----可扩展性----
supervisor是个开源软件,牛逼点的,可以直接去改软件。不过咱们大多数人还是老老实实研究supervisot提供的接口吧,supervisor主要提供了两个可扩展的功能。一个是event机制,这个就是楼主这两天干的活要用到的
东西。再一个是xml_rpc,supervisor的web管理端和远程调用的时候,就要用到它了。

-----权限----
大伙都知道linux的进程,特别是侦听在1024端口之下的进程,一般用户大多数情况下,是不能对其进行控制的。想要控制的话,必须要有root权限。而supervisor提供了一个功能,可以为supervisord或者每个子进程,
设置一个非root的user,这个user就可以管理它对应的进程了。

----兼容性,稳定性----

二、组成部分

  • supervisord:服务守护进程

  • supervisorctl:命令行客户端

  • Web Server:提供与supervisorctl功能相当的WEB操作界面

  • XML-RPC Interface:XML-RPC接口

三、安装和配置

centos平台下可直接用过YUM源安装

[root@op-zhongkong ~]# yum install supervisor
[root@op-zhongkong ~]# chkconfig supervisord on

服务器启停

[root@op-zhongkong ~]# /etc/init.d/supervisord {start|stop|status|restart|reload|force-reload|condrestart}

日志

/var/log/supervisor/supervisord.log

配置文件

[root@op-zhongkong ~]# vim /etc/supervisord.conf

需要重点关注的是以部分

[program:x]中配置要监控的进程

配置文件详解

[unix_http_server]           
file=/tmp/supervisor.sock   ; socket文件的路径,supervisorctl用XML_RPC和supervisord通信就是通过它进行
                              的。如果不设置的话,supervisorctl也就不能用了 
                              不设置的话,默认为none。 非必须设置       
;chmod=0700                 ; 这个简单,就是修改上面的那个socket文件的权限为0700
                              不设置的话,默认为0700。 非必须设置
;chown=nobody:nogroup       ; 这个一样,修改上面的那个socket文件的属组为user.group
                              不设置的话,默认为启动supervisord进程的用户及属组。非必须设置
;username=user              ; 使用supervisorctl连接的时候,认证的用户
                               不设置的话,默认为不需要用户。 非必须设置
;password=123               ; 和上面的用户名对应的密码,可以直接使用明码,也可以使用SHA加密
                              如:{SHA}82ab876d1387bfafe46cc1c8a2ef074eae50cb1d
                              默认不设置。。。非必须设置

;[inet_http_server]         ; 侦听在TCP上的socket,Web Server和远程的supervisorctl都要用到他
                              不设置的话,默认为不开启。非必须设置
;port=127.0.0.1:9001        ; 这个是侦听的IP和端口,侦听所有IP用 :9001或*:9001。
                              这个必须设置,只要上面的[inet_http_server]开启了,就必须设置它
;username=user              ; 这个和上面的uinx_http_server一个样。非必须设置
;password=123               ; 这个也一个样。非必须设置

[supervisord]                ;这个主要是定义supervisord这个服务端进程的一些参数的
                              这个必须设置,不设置,supervisor就不用干活了
logfile=/tmp/supervisord.log ; 这个是supervisord这个主进程的日志路径,注意和子进程的日志不搭嘎。
                               默认路径$CWD/supervisord.log,$CWD是当前目录。。非必须设置
logfile_maxbytes=50MB        ; 这个是上面那个日志文件的最大的大小,当超过50M的时候,会生成一个新的日
                               志文件。当设置为0时,表示不限制文件大小
                               默认值是50M,非必须设置。             
logfile_backups=10           ; 日志文件保持的数量,上面的日志文件大于50M时,就会生成一个新文件。文件
                               数量大于10时,最初的老文件被新文件覆盖,文件数量将保持为10
                               当设置为0时,表示不限制文件的数量。
                               默认情况下为10。。。非必须设置
loglevel=info                ; 日志级别,有critical, error, warn, info, debug, trace, or blather等
                               默认为info。。。非必须设置项
pidfile=/tmp/supervisord.pid ; supervisord的pid文件路径。
                               默认为$CWD/supervisord.pid。。。非必须设置
nodaemon=false               ; 如果是true,supervisord进程将在前台运行
                               默认为false,也就是后台以守护进程运行。。。非必须设置
minfds=1024                  ; 这个是最少系统空闲的文件描述符,低于这个值supervisor将不会启动。
                               系统的文件描述符在这里设置cat /proc/sys/fs/file-max
                               默认情况下为1024。。。非必须设置
minprocs=200                 ; 最小可用的进程描述符,低于这个值supervisor也将不会正常启动。
                              ulimit  -u这个命令,可以查看linux下面用户的最大进程数
                              默认为200。。。非必须设置
;umask=022                   ; 进程创建文件的掩码
                               默认为022。。非必须设置项
;user=chrism                 ; 这个参数可以设置一个非root用户,当我们以root用户启动supervisord之后。
                               我这里面设置的这个用户,也可以对supervisord进行管理
                               默认情况是不设置。。。非必须设置项
;identifier=supervisor       ; 这个参数是supervisord的标识符,主要是给XML_RPC用的。当你有多个
                               supervisor的时候,而且想调用XML_RPC统一管理,就需要为每个
                               supervisor设置不同的标识符了
                               默认是supervisord。。。非必需设置
;directory=/tmp              ; 这个参数是当supervisord作为守护进程运行的时候,设置这个参数的话,启动
                               supervisord进程之前,会先切换到这个目录
                               默认不设置。。。非必须设置
;nocleanup=true              ; 这个参数当为false的时候,会在supervisord进程启动的时候,把以前子进程
                               产生的日志文件(路径为AUTO的情况下)清除掉。有时候咱们想要看历史日志,当
                               然不想日志被清除了。所以可以设置为true
                               默认是false,有调试需求的同学可以设置为true。。。非必须设置
;childlogdir=/tmp            ; 当子进程日志路径为AUTO的时候,子进程日志文件的存放路径。
                               默认路径是这个东西,执行下面的这个命令看看就OK了,处理的东西就默认路径
                               python -c "import tempfile;print tempfile.gettempdir()"
                               非必须设置
;environment=KEY="value"     ; 这个是用来设置环境变量的,supervisord在linux中启动默认继承了linux的
                               环境变量,在这里可以设置supervisord进程特有的其他环境变量。
                               supervisord启动子进程时,子进程会拷贝父进程的内存空间内容。 所以设置的
                               这些环境变量也会被子进程继承。
                               小例子:environment=name="haha",age="hehe"
                               默认为不设置。。。非必须设置
;strip_ansi=false            ; 这个选项如果设置为true,会清除子进程日志中的所有ANSI 序列。什么是ANSI
                               序列呢?就是我们的n,t这些东西。
                               默认为false。。。非必须设置

; 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]    ;这个选项是给XML_RPC用的,当然你如果想使用supervisord或者web server 这
                              个选项必须要开启的
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]              ;这个主要是针对supervisorctl的一些配置 
serverurl=unix:///tmp/supervisor.sock ; 这个是supervisorctl本地连接supervisord的时候,本地UNIX socket
                                        路径,注意这个是和前面的[unix_http_server]对应的
                                        默认值就是unix:///tmp/supervisor.sock。。非必须设置
;serverurl=http://127.0.0.1:9001 ; 这个是supervisorctl远程连接supervisord的时候,用到的TCP socket路径
                                   注意这个和前面的[inet_http_server]对应
                                   默认就是http://127.0.0.1:9001。。。非必须项

;username=chris              ; 用户名
                               默认空。。非必须设置
;password=123                ; 密码
                              默认空。。非必须设置
;prompt=mysupervisor         ; 输入用户名密码时候的提示符
                               默认supervisor。。非必须设置
;history_file=~/.sc_history  ; 这个参数和shell中的history类似,我们可以用上下键来查找前面执行过的命令
                               默认是no file的。。所以我们想要有这种功能,必须指定一个文件。。。非
                               必须设置

; The below sample program section shows all possible program subsection values,
; create one or more 'real' program: sections to be able to control them under
; supervisor.

;[program:theprogramname]      ;这个就是咱们要管理的子进程了,":"后面的是名字,最好别乱写和实际进程
                                有点关联最好。这样的program我们可以设置一个或多个,一个program就是
                                要被管理的一个进程
;command=/bin/cat              ; 这个就是我们的要启动进程的命令路径了,可以带参数
                                例子:/home/test.py -a 'hehe'
                                有一点需要注意的是,我们的command只能是那种在终端运行的进程,不能是
                                守护进程。这个想想也知道了,比如说command=service httpd start。
                                httpd这个进程被linux的service管理了,我们的supervisor再去启动这个命令
                                这已经不是严格意义的子进程了。
                                这个是个必须设置的项
;process_name=%(program_name)s ; 这个是进程名,如果我们下面的numprocs参数为1的话,就不用管这个参数
                                 了,它默认值%(program_name)s也就是上面的那个program冒号后面的名字,
                                 但是如果numprocs为多个的话,那就不能这么干了。想想也知道,不可能每个
                                 进程都用同一个进程名吧。


;numprocs=1                    ; 启动进程的数目。当不为1时,就是进程池的概念,注意process_name的设置
                                 默认为1    。。非必须设置
;directory=/tmp                ; 进程运行前,会前切换到这个目录
                                 默认不设置。。。非必须设置
;umask=022                     ; 进程掩码,默认none,非必须
;priority=999                  ; 子进程启动关闭优先级,优先级低的,最先启动,关闭的时候最后关闭
                                 默认值为999 。。非必须设置
;autostart=true                ; 如果是true的话,子进程将在supervisord启动后被自动启动
                                 默认就是true   。。非必须设置
;autorestart=unexpected        ; 这个是设置子进程挂掉后自动重启的情况,有三个选项,false,unexpected
                                 和true。如果为false的时候,无论什么情况下,都不会被重新启动,
                                 如果为unexpected,只有当进程的退出码不在下面的exitcodes里面定义的退
                                 出码的时候,才会被自动重启。当为true的时候,只要子进程挂掉,将会被无
                                 条件的重启
;startsecs=1                   ; 这个选项是子进程启动多少秒之后,此时状态如果是running,则我们认为启
                                 动成功了
                                 默认值为1 。。非必须设置
;startretries=3                ; 当进程启动失败后,最大尝试启动的次数。。当超过3次后,supervisor将把
                                 此进程的状态置为FAIL
                                 默认值为3 。。非必须设置
;exitcodes=0,2                 ; 注意和上面的的autorestart=unexpected对应。。exitcodes里面的定义的
                                 退出码是expected的。
;stopsignal=QUIT               ; 进程停止信号,可以为TERM, HUP, INT, QUIT, KILL, USR1, or USR2等信号
                                  默认为TERM 。。当用设定的信号去干掉进程,退出码会被认为是expected
                                  非必须设置
;stopwaitsecs=10               ; 这个是当我们向子进程发送stopsignal信号后,到系统返回信息
                                 给supervisord,所等待的最大时间。 超过这个时间,supervisord会向该
                                 子进程发送一个强制kill的信号。
                                 默认为10秒。。非必须设置
;stopasgroup=false             ; 这个东西主要用于,supervisord管理的子进程,这个子进程本身还有
                                 子进程。那么我们如果仅仅干掉supervisord的子进程的话,子进程的子进程
                                 有可能会变成孤儿进程。所以咱们可以设置可个选项,把整个该子进程的
                                 整个进程组都干掉。 设置为true的话,一般killasgroup也会被设置为true。
                                 需要注意的是,该选项发送的是stop信号
                                 默认为false。。非必须设置。。
;killasgroup=false             ; 这个和上面的stopasgroup类似,不过发送的是kill信号
;user=chrism                   ; 如果supervisord是root启动,我们在这里设置这个非root用户,可以用来
                                 管理该program
                                 默认不设置。。。非必须设置项
;redirect_stderr=true          ; 如果为true,则stderr的日志会被写入stdout日志文件中
                                 默认为false,非必须设置
;stdout_logfile=/a/path        ; 子进程的stdout的日志路径,可以指定路径,AUTO,none等三个选项。
                                 设置为none的话,将没有日志产生。设置为AUTO的话,将随机找一个地方
                                 生成日志文件,而且当supervisord重新启动的时候,以前的日志文件会被
                                 清空。当 redirect_stderr=true的时候,sterr也会写进这个日志文件
;stdout_logfile_maxbytes=1MB   ; 日志文件最大大小,和[supervisord]中定义的一样。默认为50
;stdout_logfile_backups=10     ; 和[supervisord]定义的一样。默认10
;stdout_capture_maxbytes=1MB   ; 这个东西是设定capture管道的大小,当值不为0的时候,子进程可以从stdout
                                 发送信息,而supervisor可以根据信息,发送相应的event。
                                 默认为0,为0的时候表达关闭管道。。。非必须项
;stdout_events_enabled=false   ; 当设置为ture的时候,当子进程由stdout向文件描述符中写日志的时候,将
                                 触发supervisord发送PROCESS_LOG_STDOUT类型的event
                                 默认为false。。。非必须设置
;stderr_logfile=/a/path        ; 这个东西是设置stderr写的日志路径,当redirect_stderr=true。这个就不用
                                 设置了,设置了也是白搭。因为它会被写入stdout_logfile的同一个文件中
                                 默认为AUTO,也就是随便找个地存,supervisord重启被清空。。非必须设置
;stderr_logfile_maxbytes=1MB   ; 这个出现好几次了,就不重复了
;stderr_logfile_backups=10     ; 这个也是
;stderr_capture_maxbytes=1MB   ; 这个一样,和stdout_capture一样。 默认为0,关闭状态
;stderr_events_enabled=false   ; 这个也是一样,默认为false
;environment=A="1",B="2"       ; 这个是该子进程的环境变量,和别的子进程是不共享的
;serverurl=AUTO                ;

; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more 'real'
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.

;[eventlistener:theeventlistenername] ;这个东西其实和program的地位是一样的,也是suopervisor启动的子进
                                       程,不过它干的活是订阅supervisord发送的event。他的名字就叫
                                       listener了。我们可以在listener里面做一系列处理,比如报警等等
                                       楼主这两天干的活,就是弄的这玩意
;command=/bin/eventlistener    ; 这个和上面的program一样,表示listener的可执行文件的路径
;process_name=%(program_name)s ; 这个也一样,进程名,当下面的numprocs为多个的时候,才需要。否则默认就
                                 OK了
;numprocs=1                    ; 相同的listener启动的个数
;events=EVENT                  ; event事件的类型,也就是说,只有写在这个地方的事件类型。才会被发送


;buffer_size=10                ; 这个是event队列缓存大小,单位不太清楚,楼主猜测应该是个吧。当buffer
                                 超过10的时候,最旧的event将会被清除,并把新的event放进去。
                                 默认值为10。。非必须选项
;directory=/tmp                ; 进程执行前,会切换到这个目录下执行
                                 默认为不切换。。。非必须
;umask=022                     ; 淹没,默认为none,不说了
;priority=-1                   ; 启动优先级,默认-1,也不扯了
;autostart=true                ; 是否随supervisord启动一起启动,默认true
;autorestart=unexpected        ; 是否自动重启,和program一个样,分true,false,unexpected等,注意
                                  unexpected和exitcodes的关系
;startsecs=1                   ; 也是一样,进程启动后跑了几秒钟,才被认定为成功启动,默认1
;startretries=3                ; 失败最大尝试次数,默认3
;exitcodes=0,2                 ; 期望或者说预料中的进程退出码,
;stopsignal=QUIT               ; 干掉进程的信号,默认为TERM,比如设置为QUIT,那么如果QUIT来干这个进程
                                 那么会被认为是正常维护,退出码也被认为是expected中的
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false             ; send stop signal to the UNIX process group (default false)
;killasgroup=false             ; SIGKILL the UNIX process group (def false)
;user=chrism                   ;设置普通用户,可以用来管理该listener进程。
                                默认为空。。非必须设置
;redirect_stderr=true          ; 为true的话,stderr的log会并入stdout的log里面
                                默认为false。。。非必须设置
;stdout_logfile=/a/path        ; 这个不说了,好几遍了
;stdout_logfile_maxbytes=1MB   ; 这个也是
;stdout_logfile_backups=10     ; 这个也是
;stdout_events_enabled=false   ; 这个其实是错的,listener是不能发送event
;stderr_logfile=/a/path        ; 这个也是
;stderr_logfile_maxbytes=1MB   ; 这个也是
;stderr_logfile_backups        ; 这个不说了
;stderr_events_enabled=false   ; 这个也是错的,listener不能发送event
;environment=A="1",B="2"       ; 这个是该子进程的环境变量
                                 默认为空。。。非必须设置
;serverurl=AUTO                ; override serverurl computation (childutils)

; The below sample group section shows all possible group values,
; create one or more 'real' group: sections to create "heterogeneous"
; process groups.

;[group:thegroupname]  ;这个东西就是给programs分组,划分到组里面的program。我们就不用一个一个去操作了
                         我们可以对组名进行统一的操作。 注意:program被划分到组里面之后,就相当于原来
                         的配置从supervisor的配置文件里消失了。。。supervisor只会对组进行管理,而不再
                         会对组里面的单个program进行管理了
;programs=progname1,progname2  ; 组成员,用逗号分开
                                 这个是个必须的设置项
;priority=999                  ; 优先级,相对于组和组之间说的
                                 默认999。。非必须选项

; 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]                         ;这个东西挺有用的,当我们要管理的进程很多的时候,写在一个文件里面
                                    就有点大了。我们可以把配置信息写到多个文件中,然后include过来
;files = relative/directory/*.ini

配置样例

[supervisord] 
http_port=/var/tmp/supervisor.sock ; (default is to run a UNIX domain socket server) 
;http_port=127.0.0.1:9001  ; (alternately, ip_address:port specifies AF_INET) 
;sockchmod=0700              ; AF_UNIX socketmode (AF_INET ignore, default 0700) 
;sockchown=nobody.nogroup     ; AF_UNIX socket uid.gid owner (AF_INET ignores) 
;umask=022                   ; (process file creation umask;default 022) 
logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) 
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB) 
logfile_backups=10          ; (num of main logfile rotation backups;default 10) 
loglevel=info               ; (logging level;default info; others: debug,warn) 
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) 
nodaemon=false              ; (start in foreground if true;default false) 
minfds=1024                 ; (min. avail startup file descriptors;default 1024) 
minprocs=200                ; (min. avail process descriptors;default 200) 

;nocleanup=true              ; (don't clean up tempfiles at start;default false) 
;http_username=user          ; (default is no username (open system)) 
;http_password=123           ; (default is no password (open system)) 
;childlogdir=/tmp            ; ('AUTO' child log dir, default $TEMP) 
;user=chrism                 ; (default is current user, required if root) 
;directory=/tmp              ; (default is not to cd during start) 
;environment=KEY=value       ; (key value pairs to add to environment) 

[supervisorctl] 
serverurl=unix:///var/tmp/supervisor.sock ; use a unix:// URL  for a unix socket 
;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket 
;username=chris              ; should be same as http_username if set 
;password=123                ; should be same as http_password if set 
;prompt=mysupervisor         ; cmd line prompt (default "supervisor") 

; The below sample program section shows all possible program subsection values, 
; create one or more 'real' program: sections to be able to control them under 
; supervisor. 

;[program:example] 
;command=/bin/echo; the program (relative uses PATH, can take args) 
;priority=999                ; the relative start priority (default 999) 
;autostart=true              ; start at supervisord start (default: true) 
;autorestart=true            ; retstart at unexpected quit (default: true) 
;startsecs=10                ; number of secs prog must stay running (def. 10) 
;startretries=3              ; max # of serial start failures (default 3) 
;exitcodes=0,2               ; 'expected' exit codes for process (default 0,2) 
;stopsignal=QUIT             ; signal used to kill process (default TERM) 
;stopwaitsecs=10             ; max num secs to wait before SIGKILL (default 10) 
;user=chrism                 ; setuid to this UNIX account to run the program 
;log_stdout=true             ; if true, log program stdout (default true) 
;log_stderr=true             ; if true, log program stderr (def false) 
;logfile=/var/log/supervisor.log    ; child log path, use NONE for none; default AUTO 
;logfile_maxbytes=1MB        ; max # logfile bytes b4 rotation (default 50MB) 
;logfile_backups=10          ; # of logfile backups (default 10) 

“;”为注释。各参数的含义都很明确。可以根据官方手册结合实验来进一步深入了解。重点说几个[program:example]中的参数

;command=/bin/echo;         supervisor启动时将要开启的进程。相对或绝对路径均可。若是相对路径则会从supervisord的$PATH变中查找。命令可带参数。 
;priority=999                   指明进程启动和关闭的顺序。低优先级表明进程启动时较先启动关闭时较后关闭。高优先级表明进程启动时启动时较后启动关闭时较先关闭。 
;autostart=true                 是否随supervisord启动而启动 
;autorestart=true               进程意外退出后是否自动重启 
;startsecs=10                   进程持续运行多久才认为是启动成功 
;startretries=3                 重启失败的连续重试次数 
;exitcodes=0,2                  若autostart设置为unexpected且监控的进程并非因为supervisord停止而退出,那么如果进程的退出码不在exitcode列表中supervisord将重启进程 
;stopsignal=QUIT                杀进程的信号 
;stopwaitsecs=10                向进程发出stopsignal后等待OS向supervisord返回SIGCHILD 的时间。若超时则supervisord将使用SIGKILL杀进程 

如下看一个使用supervisor监控的配置情况(配置中的其他默认内容在此省略)

[program:worker_for_summary] 
command=/home/op1/scripts/rabbitmqclient/worker_for_summary.py 
priority=1 
log_stderr=true             ; if true, log program stderr (def false) 

[program:worker_for_detail_all] 
command=/home/op1/scripts/rabbitmqclient/worker_for_detail_all.py 
priority=1 
log_stderr=true             ; if true, log program stderr (def false) 

[program:worker_for_detail_recent_list] 
command=/home/op1/scripts/rabbitmqclient/worker_for_detail_recent_list.py 
priority=1 
log_stderr=true             ; if true, log program stderr (def false) 

[program:worker_for_detail_recent_sset] 
command=/home/op1/scripts/rabbitmqclient/worker_for_detail_recent_sset.py 
priority=1 
log_stderr=true             ; if true, log program stderr (def false) 

[program:publisher_for_summary] 
command=/home/op1/scripts/rabbitmqclient/publisher_for_summary.py 
priority=999 
log_stderr=true             ; if true, log program stderr (def false) 

[program:publisher_for_summary_nt] 
command=/home/op1/scripts/rabbitmqclient/publisher_for_summary_nt.py 
priority=999 
log_stderr=true             ; if true, log program stderr (def false) 

[program:publisher_for_detail] 
command=/home/op1/scripts/rabbitmqclient/publisher_for_detail.py 
priority=999 
log_stderr=true             ; if true, log program stderr (def false) 

[program:publisher_for_detail_nt] 
command=/home/op1/scripts/rabbitmqclient/publisher_for_detail_nt.py 
priority=999 
log_stderr=true             ; if true, log program stderr (def false) 

配置完成后启动supervisord

[root@op-zhongkong ~]# /etc/init.d/supervisord start

可以看到配置的各个进程在后台运行了起来。停掉某个进程后supervisor会马上重启该进程

停止supervisor

[root@op-zhongkong ~]# /etc/init.d/supervisord stop

可以看到配置的各个进程都停止运行了。可以通过supervisorctl查看管理监控的进程情况

[root@op-zhongkong ~]# sudo supervisorctl 
publisher_for_detail RUNNING    pid 27557, uptime 0:00:45 
publisher_for_detail_nt RUNNING    pid 27567, uptime 0:00:45 
publisher_for_summary RUNNING    pid 27566, uptime 0:00:45 
publisher_for_summary_nt RUNNING    pid 27568, uptime 0:00:45 
worker_for_detail_all RUNNING    pid 27581, uptime 0:00:45 
worker_for_detail_recent RUNNING    pid 27582, uptime 0:00:45 
worker_for_summary RUNNING    pid 27559, uptime 0:00:45 

#可通过help了解命令的更多用法 
supervisor> help 

Documented commands (type help <topic>): 
======================================== 
EOF    exit  maintail  quit    restart   start   stop 
clear  help  open      reload  shutdown  status  tail 

supervisor> help stop 
stop <processname>            Stop a process. 
stop <processname> <processname>    Stop multiple processes 
stop all                Stop all processes 
  When all processes are stopped, they are stopped in 
  reverse priority order (see config file) 
supervisor> help status 
status          Get all process status info. 
status <name>     Get status on a single process by name. 
status <name> <name>    Get status on multiple named processes. 

#停止某个进程 
supervisor> stop publisher_for_summary 
publisher_for_summary: stopped 

#查看此时此刻的状态 
supervisor> status 
publisher_for_detail RUNNING    pid 27557, uptime 0:05:41 
publisher_for_detail_nt RUNNING    pid 27567, uptime 0:05:41 
publisher_for_summary STOPPED    Feb 27 02:48 PM 
publisher_for_summary_nt RUNNING    pid 27568, uptime 0:05:41 
worker_for_detail_all RUNNING    pid 27581, uptime 0:05:41 
worker_for_detail_recent RUNNING    pid 27582, uptime 0:05:41 
worker_for_summary RUNNING    pid 27559, uptime 0:05:41 
#发现被supervisorctl停掉的进程不会被自动重启 

#开启刚才停掉的进程 
supervisor> start publisher_for_summary 
publisher_for_summary: started 
supervisor> status 
publisher_for_detail RUNNING    pid 27557, uptime 0:08:02 
publisher_for_detail_nt RUNNING    pid 27567, uptime 0:08:02 
publisher_for_summary RUNNING    pid 3035, uptime 0:00:04 
publisher_for_summary_nt RUNNING    pid 27568, uptime 0:08:02 
worker_for_detail_all RUNNING    pid 27581, uptime 0:08:02 
worker_for_detail_recent RUNNING    pid 27582, uptime 0:08:02 
worker_for_summary RUNNING    pid 27559, uptime 0:08:02 

#停掉所有进程 
supervisor> stop all 
worker_for_detail_recent: stopped 
worker_for_detail_all: stopped 
publisher_for_summary_nt: stopped 
publisher_for_detail_nt: stopped 
publisher_for_summary: stopped 
worker_for_summary: stopped 
publisher_for_detail: stopped 
supervisor> status 
publisher_for_detail STOPPED    Feb 27 02:51 PM 
publisher_for_detail_nt STOPPED    Feb 27 02:51 PM 
publisher_for_summary STOPPED    Feb 27 02:51 PM 
publisher_for_summary_nt STOPPED    Feb 27 02:51 PM 
worker_for_detail_all STOPPED    Feb 27 02:51 PM 
worker_for_detail_recent STOPPED    Feb 27 02:51 PM 
worker_for_summary STOPPED    Feb 27 02:51 PM 

#开启所有进程 
supervisor> start all 
publisher_for_detail: started 
worker_for_summary: started 
publisher_for_summary: started 
publisher_for_detail_nt: started 
publisher_for_summary_nt: started 
worker_for_detail_all: started 
worker_for_detail_recent: started 
supervisor> status 
publisher_for_detail RUNNING    pid 5111, uptime 0:00:15 
publisher_for_detail_nt RUNNING    pid 5141, uptime 0:00:15 
publisher_for_summary RUNNING    pid 5135, uptime 0:00:15 
publisher_for_summary_nt RUNNING    pid 5147, uptime 0:00:15 
worker_for_detail_all RUNNING    pid 5153, uptime 0:00:15 
worker_for_detail_recent RUNNING    pid 5159, uptime 0:00:14 
worker_for_summary RUNNING    pid 5112, uptime 0:00:15 

————————————下面是线上用过的supervisor监控python程序的一个配置———————-

[program:xcspam]
command=/usr/bin/python /app/web/xcspam/bin/main.py --port=93%(process_num)02d
process_name=%(program_name)s_%(process_num)02d
numprocs=16
numprocs_start=1
directory=/app/web/xcspam
user=work
autostart=true
autorestart=true
stopsignal=QUIT
stdout_logfile=/data/log/xcspam/xcspam.log
stderr_logfile=/data/log/xcspam/xcspam_error.log
stdout_logfile_maxbytes=0
stderr_logfile_maxbytes=0
environment=PYTHONPATH=/app/web/xcspam, ZUIYOU_ENV=production

[program:report]
command=/usr/bin/celery -A worker worker -Q report --loglevel=INFO
directory=/app/web/xcspam/bin
user=work
autostart=true
autorestart=true
stopsignal=QUIT
stdout_logfile=/data/log/xcspam/celery-report.log
stderr_logfile=/data/log/xcspam/celery-report_error.log
stdout_logfile_maxbytes=0
stderr_logfile_maxbytes=0
environment=PYTHONPATH=/app/web/xcspam, ZUIYOU_ENV=production

[program:antiwater]
command=/usr/bin/celery -A worker worker -Q antiwater --loglevel=INFO
directory=/app/web/xcspam/bin
user=work
autostart=true
autorestart=true
stopsignal=QUIT
stdout_logfile=/data/log/xcspam/celery-antiwater.log
stderr_logfile=/data/log/xcspam/celery-antiwater_error.log
stdout_logfile_maxbytes=0
stderr_logfile_maxbytes=0
environment=PYTHONPATH=/app/web/xcspam, ZUIYOU_ENV=production

[program:celery-flower]
command=/usr/bin/celery flower -A worker --address=10.31.51.232 --port=9330
directory=/app/web/xcspam/bin
user=work
autostart=true
autorestart=true
stopsignal=QUIT
stdout_logfile=/data/log/xcspam/celery-flower.log
stderr_logfile=/data/log/xcspam/celery-flower_error.log
stdout_logfile_maxbytes=0
stderr_logfile_maxbytes=0
environment=PYTHONPATH=/app/web/xcspam, ZUIYOU_ENV=production

由于默默使用supervisorctl命令查看监控的程序运行状态是交互式的,所以自己写了个简单的脚本命令superctl,可以直接查看

[root@op-zhongkong ~]# cat /usr/local/bin/superctl
/usr/bin/python /usr/local/bin/superctl -c /etc/supervisord.conf $1 $2
[root@op-zhongkong ~]# chmod 755 /usr/local/bin/superctl

[root@op-zhongkong ~]#  superctl status
antiwater                        RUNNING   pid 17172, uptime 0:21:23
celery-flower                    RUNNING   pid 20507, uptime 0:18:52
report                           RUNNING   pid 16752, uptime 0:21:35
xcspam:xcspam_01                 RUNNING   pid 14594, uptime 0:23:00
xcspam:xcspam_02                 RUNNING   pid 14526, uptime 0:23:01
xcspam:xcspam_03                 RUNNING   pid 14551, uptime 0:23:01
xcspam:xcspam_04                 RUNNING   pid 14641, uptime 0:22:59
xcspam:xcspam_05                 RUNNING   pid 14642, uptime 0:22:58
xcspam:xcspam_06                 RUNNING   pid 14608, uptime 0:22:59
xcspam:xcspam_07                 RUNNING   pid 14618, uptime 0:22:59
xcspam:xcspam_08                 RUNNING   pid 14674, uptime 0:22:58
xcspam:xcspam_09                 RUNNING   pid 14690, uptime 0:22:58
xcspam:xcspam_10                 RUNNING   pid 14498, uptime 0:23:02
xcspam:xcspam_11                 RUNNING   pid 14462, uptime 0:23:03
xcspam:xcspam_12                 RUNNING   pid 14463, uptime 0:23:03
xcspam:xcspam_13                 RUNNING   pid 14579, uptime 0:23:00
xcspam:xcspam_14                 RUNNING   pid 14749, uptime 0:22:58
xcspam:xcspam_15                 RUNNING   pid 14669, uptime 0:22:58
xcspam:xcspam_16                 RUNNING   pid 14512, uptime 0:23:02

docker容器内通过supervisor来守护进程

安装:

可通过easy install supervisor或pip install supervisor,当然还可以通过下载源码通过Python setup.py install 来安装(注意:要在python2.x下进行安装)

还可以通过linxu下的包管理来安装,如yum install supervisor

使用:

.为要维护的进程创建.ini文件,并放到/etc/supervisor.d目录下
.启动supervisord服务
/usr/bin/supervisord -c /etc/supervisor.conf

可通过supervisorctl status 查看supervisord当前管理的所有进程的状态

遇到的问题:

通过docker run -d 方式启动容器报“Unlinking stale socket /tmp/supervisor.sock”错误,而通过docker run -it 启动后手动执行 /usr/bin/supervisord -c /etc/supervisor.conf则没问题

解决:

将Dockerfile中的CMD [“/usr/bin/supervisord”, “-c”, “/etc/supervisord.conf”] 修改成ENTRYPOINT [“/usr/bin/supervisord”, “-n”, “-c”, “/etc/supervisord.conf”] 重新生成镜像,用该镜像启动容器docker run -d即可,问题解决。

linux后台进程管理工具-supervisor

安装环境为:centos,如果是ubuntu的话命令可能会不一样。

Supervisor 是一个用python编写的进程管理工具,能将一个普通的命令行进程变为后台的deamon,方便管理。

安装supervisor

可以通过yum和pip来安装,可以根据个人喜好来使用,我用yum来安装的:

yum -y install supervisor //-y 为自动安装,不会再弹确认提醒

yum安装完成以后会在 /etc/下创建 supervisord.conf 配置文件及supervisord.d文件夹。

supervisord.conf 选项及值可以去supervisor官网查看 //有时间整理下写上来

配置supervisor

我们为自己开发的应用程序编写一个配置文件,放在/etc/supervisord.d下,以.conf或.ini结尾,下面写个简单的例子,详细的可以去看supervisor官网

[program:app]
command=/usr/bin/xxx    //运行程序的命令
directory=/tmp/xxx      //程序的目录
user=xxx                //运行程序的用户身份

启动supervisor服务

supervisord -c /etc/supervisor.conf

用supervisor客户端管理工具supervisorctl,来管理进程。

$ supervisorctl status      //查看状态
$ supervisorctl stop xxx    //停止应用
$ supervisorctl start xxx   //启动应用
$ supervisorctl restart xxx //重启应用