Supervisor 進程控制系統

介紹

Supervisor是一個進程控制系統,它的做用是:你的Nginx,Tomcat,memcache,Redis...會崩麼,不會?好吧,那你本身寫的服務器監測腳本呢?好吧,不要再糾結了,交給Supervisor吧,它會幫你維護這些,即便它們不當心崩了,Supervisor會幫你看住它們,維護它們。這種方式能夠解決nginx、php_fpm在一個docker容器裏開機自啓動,不須要人工操做php

安裝

一、yum -y install supervisorhtml

配置文件解釋

[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結束的配置文件

配置本身的文件

注意:supervisor不能監控後臺進程,command 不能爲後臺運行命令
因此服務都只能放在前臺運行,不能再後臺python

一、vi /etc/supervisord.conf (只改後面的include就能夠了)nginx

; 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".
;  - Comments must have a leading space: "a=b ;comment" not "a=b;comment".

[unix_http_server]
file=/tmp/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)
logfile_maxbytes=50MB        ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10           ; (num of main logfile rotation backups;default 10)
loglevel=info                ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/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 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:///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")
;history_file=~/.sc_history  ; use readline history if available

; 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]
;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 (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 (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 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]
;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 (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 (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 below sample group section 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/*.conf

方式一:
監控nginx:
[root@docker etc]# cat /etc/supervisord.d/nginx.conf
[program:nginx]
command=nginx -g "daemon off;"
user=root
stdout_logfile=/tmp/nginx.log
autostart=true
autorestart=true
startsecs=5
stopasgroup=true
ikillasgroup=true
startretries=1
redirect_stderr=trueweb

監聽php:
[root@docker etc]# cat /etc/supervisord.d/php.conf
[program:php-fpm]
command=php-fpm
user=root
stdout_logfile=/tmp/php-fpm.log
autostart=true
autorestart=true
startsecs=10
stopasgroup=true
ikillasgroup=true
startretries=1
redirect_stderr=truedocker

一、啓動服務:/usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf
二、如果後續更改了配置文件:supervisorctl update 或者supervisorctl reload 便可shell

驗證:
Supervisor 進程控制系統apache

方式二:寫腳本監聽tomcat

[root@docker shell]# cat check_nginx.sh 安全

#!/bin/bash
#日誌文件
logfile="/data/logs/nginx.log"
#檢測本機nginx_php服務是否中止
check_nginx(){
    local nginxstat=`netstat -nutlp| grep "0.0.0.0:80" | wc -l`
    if [ ${nginxstat} -ne 1 ];then
        echo "`date`" >> ${logfile}
        echo "nginx服務已中止" >> ${logfile}
        echo "nginx服務開始前臺啓動" >> ${logfile}
        nginx -g "daemon off;"
        if [ $? -eq 0 ];then
            echo "nginx服務已啓動" >> ${logfile}
        else
            echo "nginx服務啓動失敗" >> ${logfile}
        fi

    fi
}

while : 
do
    check_nginx
    sleep 10
done

[root@docker shell]# cat check_php.sh

#!/bin/bash
#日誌文件
logfile="/data/logs/php-fpm.log"
#檢測本機php-fpm服務是否中止

check_php(){
    local phpstat=`netstat -nutlp| grep "127.0.0.1:9000" | wc -l`
    if [ "$phpstat" -ne 1 ];then
        echo "`date`" >> ${logfile}
        echo "php-fpm服務已中止" >> ${logfile}
        echo "php-fpm服務開始前臺啓動" >> ${logfile}
        php-fpm
        if [ $? -eq 0 ];then
            echo "php-fpm服務已啓動" >> ${logfile}
        else
            echo "php-fpm服務啓動失敗" >> ${logfile}
        fi

    fi
}

while : 
do
    check_php
    sleep 10
done

一、更新配置文件
supervisorctl reload

二、驗證
Supervisor 進程控制系統

修改了nginx/php-fpm配置文件,須要從新加載
一、nginx -s reload
二、pkill php-fpm 等10s,再查看php-fpm有無啓動便可

經常使用命令

supervisorctl 是 supervisord的命令行客戶端工具:

supervisorctl status:查看全部進程的狀態
supervisorctl stop es:中止es
supervisorctl start es:啓動es
supervisorctl restart es: 重啓es
supervisorctl update :配置文件修改後可使用該命令加載新的配置
supervisorctl reload: 從新啓動配置中的全部程序
相關文章
相關標籤/搜索