轻松使用supervisor管理nginx进程

supervisor

Supervisor是用Python开发的一套通用的进程管理程序,能将一个普通的命令行进程变为后台daemon,并监控进程状态,异常退出时能自动重启。只要在supervisor的配置文件中,把要管理的进程的可执行文件的路径写进去即可。当子进程挂掉的时候,父进程可以准确获取子进程挂掉的信息的,可以选择是否自己启动和报警。supervisor还提供了一个功能,可以为supervisord或者每个子进程,设置一个非root的user,这个user就可以管理它对应的进程。
标题写的是Nginx,其实管理其他的进程也是一样的道理

supervisor的下载

supervisor是基于python写的,所以我们用pip来安装。(我的操作目录是/home/work/super,操作用户是root,如果你不是root身份,有的命令可能需要加上sudo提权)
我的操作目录是 /home/work/super

[ec2-user@ip-172-14-28-13 ~]$ wget https://bootstrap.pypa.io/get-pip.py --no-check-certificate
[ec2-user@ip-172-14-28-13 ~]$ python get-pip.py
[ec2-user@ip-172-14-28-13 ~]$ pip2 install supervisor

生成supervisor配置文件

supervisor默认是没有配置文件的,所以如果不想从头“写”起,我们可以自己手动生成一份默认的配置文件。

[ec2-user@ip-172-14-28-13 ~]$ echo_ supervisord_conf  > /home/work/super/supervisord.conf

【注:配置文件里面,前面加 ; 表示注释】

开始配置配置文件

先贴一份自己用的,比较懒,带注释的也贴出来了。【后面还有一份带讲解的配置文件。想深入了解的小伙伴可以取看一下】

首先是supervisor本身的配置文件【偷懒,带这注释直接全部贴出来了】
[ec2-user@ip-172-14-28-13 ~]$ cat /home/work/super/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]
file=/home/work/super/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=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)

[supervisord]
logfile=/home/work/super/supervisord.log ; main log file; default $CWD/supervisord.log
logfile_maxbytes=100MB        ; max main logfile bytes b4 rotation; default 50MB
logfile_backups=5           ; # of main logfile backups; 0 means none, default 10
loglevel=info                ; log level; default info; others: debug,warn,trace
pidfile=/home/work/super/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
;user=chrism                 ; 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]
serverurl=unix:///home/work/super/supervisor.sock ; use a unix:// URL  for a unix socket
serverurl=http://0.0.0.0: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=30                   ; # 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=50MB   ; 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 = /home/work/super/conf.d/*_super.conf

接下来是对配置文件的一些选项进行讲解了,说的不是很全面,大伙看看就好

[unix_http_server]
file=/tmp/supervisor.sock   ;
;socket文件的路径,如果不设置的话,supervisorctl命令不能使用                
[inet_http_server]
port=127.0.0.1:9001            ;
; 这个是侦听的IP和端口,侦听所有IP:9001*:9001[supervisord]     
;定义supervisord服务端进程的一些参数。这个不能出错,搞错一个,supervisor就不用干活了
logfile=/tmp/supervisord.log ;  
;supervisord主进程的日志路径,要和子进程日志区分开
logfile_maxbytes=100MB        ;
;当日志文件超过50M,会生成一个新的日志文件。0表示不限制文件大小
logfile_backups=5           ;
;日志文件保持的数量,supervisor在启动程序时,会自动创建10个buckup文件,用于log rotate,当设置为0时,表示不限制文件的数量。
loglevel=info                ; 
;日志级别,默认是 info,其他的还有 debug,warn,trace
pidfile=/home/work/super/supervisord.pid ;     
;supervisord的pid文件路径
nodaemon=false               ;    
;true表示supervisord进程将在前台运行。默认为false,以守护进程运行
minfds=1024                  ;  
;这个是最少系统空闲的文件描述符,低于这个值supervisor将不会启动。 系统的文件描述符在这里设置cat /proc/sys/fs/file-max,默认情况下为1024
minprocs=200                 ;
;最小可用的进程描述符,低于这个值supervisor也将不会正常启动。ulimit  -u可以查看linux下面用户的最大进程数,默认为200
[rpcinterface:supervisor]         
;这个选项是给XML_RPC用的
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]      
;这个主要是针对supervisorctl的一些配置
serverurl=unix:///home/work/super/supervisor.sock ;   
;这个是supervisorctl本地连接supervisord的时候,本地UNIX socket路径,是和前面的[unix_http_server]对应的, 默认值就是unix:///tmp/supervisor.sock
serverurl=http://0.0.0.0:9001 ;  
;supervisorctl远程连接supervisord的时候,用到的TCP socket路径,这个和前面的[inet_http_server]对应,默认就是http://127.0.0.1:9001
[include]
files = /home/work/super/*_super.conf   
;这个很重要,当我们要管理的进程很多的时候,写在一个文件里面  会显得很臃肿。所以可以把配置信息写到多个文件中,然后include调用。

开始配置supervisor调用的文件

老规矩,先贴一个自己用的 【nginx的这个启动命令默认是后台启动,supervisor不能监控后台程序,所以就会一直执行这个命令,不断的启动Nginx,就会报错。 加上-g ‘daemon off;’ 这个参数可解决这问题。】

[ec2-user@ip-172-14-28-13 ~]$ cat /home/work/super/conf.d/nginx_super.conf

[program: nginx]
command=/usr/local/nginx/sbin/nginx  -g 'daemon off;'
directory=/home/work ;
autorestart=true ;
autostart=true ;
stderr_logfile=/home/work/super/error.log ;
stdout_logfile=/home/work/super/stdout.log ;
environment=ASPNETCORE_ENVIRONMENT=Production ;
user=root ;
stopsignal=INT
startsecs=10 ;
startretries=5 ;
stopasgroup=true

调用的配置文件的讲解

[program: nginx]    
;管理的子进程。后面的是名字,最好写的具有代表性,避免日后”认错“
command=/usr/local/nginx/sbin/nginx  -g 'daemon off;'    
;我们的要启动进程的命令路径,可以带参数。
directory=/root ;   
;进程运行前,会先切换到这个目录
autorestart=true;设置子进程挂掉后自动重启的情况,有三个选项,false,unexpected和truefalse表示无论什么情况下,都不会被重新启动;unexpected表示只有当进程的退出码不在下面的exitcodes里面定义的退出码的时候,才会被自动重启。当为true的时候,只要子进程挂掉,将会被无条件的重启
autostart=true ;    
;如果是true的话,子进程将在supervisord启动后被自动启动,默认就是true
stderr_logfile=/home/work/super/nginx_error.log ;   
;日志,没什么好说的
stdout_logfile=/home/work/super/nginx_stdout.log ;  
;日志
environment=ASPNETCORE_ENVIRONMENT=Production ;  
;这个是子进程的环境变量,默认为空
user=nginx ;     
;可以用来管理该program的用户
stopsignal=INT   
;进程停止信号,可以为TERM, HUP, INT, QUIT, KILL, USR1,默认为TERM
startsecs=10 ;    
;子进程启动多少秒之后,此时状态如果是running,我们认为启动成功了,默认值1
startretries=5 ;   当进程启动失败后,最大尝试的次数。当超过5次后,进程的状态变为FAIL
stopasgroup=true   
;这个东西主要用于,supervisord管理的子进程,这个子进程本身还有子进程。那么我们如果仅仅干掉supervisord的子进程的话,子进程的子进程有可能会变成孤儿进程。所以可以设置这个选项,把整个该子进程的整个进程组干掉。默认false

接近尾声

到这里基本就算是完成了,我们可以直接干掉nginx,然后再启动supervisor就可以了,它会自动把nginx启动起来

[ec2-user@ip-172-14-28-13 ~]$ /usr/local/nginx/sbin/nginx -s stop
[ec2-user@ip-172-14-28-13 ~]$ supervisord -c /home/work/super/supervisord.conf  ##启动supervisor

输入命令supervisorctl,可以进入交互界面,看到它监管的进程状态,如下

[ec2-user@ip-172-14-28-13 ~]$ supervisorctl
listener                          RUNNING   pid 8591, uptime 19:17:51
wechat                           STOPPED   Apr 01 03:44 PM
supervisor>

也可以直接用非交互的方式,在终端输入supervisorctl进行管理

[ec2-user@ip-172-14-28-13 ~]$ supervisorctl  start/stop/restart  wechat

欢迎各位指出不足 QQ:925124317

猜你喜欢

转载自blog.csdn.net/weixin_44449055/article/details/88966342