注:本文使用版本: 4.0.4 (Mac環境下)html
在項目,常常須要將一個進程設置爲守護進程(常駐進程),比較簡單的作法是 nohup + &
,稍微高級一點的作法就是使用Supervisor了。web
Supervisor包含兩部分:supervisord 和 supervisorctl。shell
啓動Supervisor的時候,本質上是啓動一個supervisord
進程,這個進程將所管理的進程做爲本身的子進程來啓動,並且能夠在所管理的進程出現崩潰時自動重啓。bash
supervisorctl
則是一個命令行管理工具,能夠執行 stop、start、restart 等命令,實現對子進程的管理。socket
# Ubuntu
apt install supervisor
# Pip
pip install supervisor
# Mac
brew install supervisor
複製代碼
# Mac (可經過 brew info supervisor 查看本身的啓動方式)
supervisord -c /usr/local/etc/supervisord.ini
# Ubuntu 宿主機
systemctl start supervisor
# Ubuntu Docker容器
sudo /etc/init.d/supervisor start
複製代碼
supervisorctl 有兩種方式與supervisord進行通訊:本地socket鏈接
和 http鏈接
。工具
supervisorctl 默認使用的是 http鏈接,因此當你未開啓http配置且執行supervisorctl
命令時,會出現以下錯誤:加密
$ supervisorctl
http://localhost:9001 refused connection
supervisor>
複製代碼
開啓http配置(注意http通訊並無加密)spa
[inet_http_server] ; inet (TCP) server disabled by default
port=127.0.0.1:9001 ; ip_address:port specifier, *:port for all iface
複製代碼
從新啓動supervisord進程命令行
supervisord -c /usr/local/etc/supervisord.inirest
若是不想開啓http配置,則每次都須要指定配置文件
supervisorctl -c /usr/local/etc/supervisord.ini
$ supervisord -v
4.0.4
1.對於Mac系統,主配置文件位於 /usr/local/etc/supervisord.ini
2.對於Ubuntu系統,主配置文件位於 /etc/supervisor/supervisord.conf
3.對於較早的版本,可能須要手動生成配置文件
echo_supervisord_conf > /etc/supervisord.conf
子進程配置文件路徑可在主配置文件中找到,個人路徑以下:
[include]
files = /usr/local/etc/supervisor.d/*.ini
複製代碼
爲了更好地說明,咱們先編寫一個Shell腳本,定時打印當前日期
#/bin/bash
while true; do
echo now: `date "+%Y-%m-%d %H:%M:%S"`
sleep 2
done
複製代碼
配置文件以下:
; 註釋使用的是分號
[program:printime]; webhook是進程名/服務名
; 啓動命令
command=bash /home/xxx/print_time.sh
; 自動重啓
autostart=true
autorestart=true
user=xxx
umask=022
; 日誌文件
stdout_logfile=/home/xxx/print_time.log
; 重定向錯誤日誌到stdout
redirect_stderr=true
;日誌級別
loglevel=info
複製代碼
更新配置並啓動服務
$ supervisorctl update
printime: added process group
$ supervisorctl
printime RUNNING pid 88295, uptime 0:00:06
複製代碼
restart:重啓進程,並不會從新讀取配置文件,因此服務實際未使用新配置
reread:只會更新配置文件,不會重啓進程,因此服務實際未使用新配置
update:更新配置文件,並重啓配置文件有更新的進程,至關於 reread + restart,因此服務會使用新配置
reload:重啓supervisord,至關於更新全部服務的配置文件,並重啓全部服務(謹慎使用)
參考:
www.onurguzel.com/supervisord…
supervisord.org/runnin g.html?highlight=reread
當使用supervisor啓動某個進程時,你會發現該進程沒法讀取系統環境變量,由於 supervisor 啓動的時候是使用 /etc/init.d 啓動,因此係統環境變量根本沒有加載起來。
解決辦法是在配置文件指定環境變量,例如:
[program:xxx]
;通常指定環境變量的方式: export SSH_KEY=xxx
;使用 supervisor 指定環境變量的方式
environment=SSH_KEY=xxx
複製代碼