lemooljiang avatar

Supervisor管理python web服务 / 网络研习社#88

lemooljiang

Published: 28 Apr 2024 › Updated: 28 Apr 2024

Supervisor管理python web服务 / 网络研习社#88

supervisor.jpg

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

因为是python开发的一个库,可以直接用pip来安装,很方便。supervisor安装完成后会生成三个执行程序:supervisord、supervisorctl、echo_supervisord_conf,分别是supervisor的守护进程服务(用于接收进程管理命令)、客户端(用于和守护进程通信,发送管理进程的指令)、生成初始配置文件程序。

pip install supervisor  #supervisor-4.2.5

echo_supervisord_conf  #查看基本配置
echo_supervisord_conf > /home/wsgi.ini #生成初始配置文件

# 配置范例
[program:wsgiX]   ;program:
;
directory=/home/knowqa 
; python api.py使gunicorn
command = /home/knowqa/know_env/bin/python /home/knowqa/know_env/bin/gunicorn -c config.py api:app
startsecs=0
stopwaitsecs=0
autostart=true          ;supervisordtornado
autorestart=true        ;supervisordtornado
redirect_stderr=true   ;stderrstdout
;print
stdout_logfile=./stdout.log
stderr_logfile=./error.log

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

;supervisord
[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=1

# 启动
supervisord -c ./wsgi.ini
//supervisord -c /home/wsgi.ini

查看运行状态

ps -ef | grep supervisord
supervisor2.jpg

看到如上所示,即运行正常。如果要停止,则直接kill, 比如: kill 197320 。命令如下:
kill pid #停止运行

在Supervisor的使用中,其中“工作目录”和 “启动命令”是最关键的两处设置,务必正确! 在“启动命令”时可以看到是使用gunicorn来启动服务的,就来补下gunicorn的设置。

Gunicorn

Gunicorn是一个unix上被广泛使用的高性能的Python WSGI UNIX HTTP Server,和大多数的web框架兼容,并具有实现简单,轻量级,高性能等特点。

pip install gunicorn

# 快速启动run.py
gunicorn --workers=4 --bind=0.0.0.0:8000 run:app

# run.py
from flask import Flask
app = Flask(__name__)

# 配置文件启动

# 配置文件范例 config.py
import multiprocessing

bind = "0.0.0.0:8000"
workers = multiprocessing.cpu_count() * 2 + 1

backlog = 2048
worker_class = "eventlet"
worker_connections = 1000
daemon = True
pidfile = 'log/gunicorn.pid'
accesslog = 'log/access.log'
errorlog = 'log/gunicorn.log'

# 启动
gunicorn --config=config.py run:app

# 服务重启、退出等
GunicorngunicornMaster PID
#方法1
pstree -ap|grep gunicorn
#方法2
ps -ef|grep gunicorn 
# 重启Gunicorn进程
HUP(线)workermaster
kill -HUP master_pid
# 优雅停止Gunicorn进程
pkill gunicorn
kill -9 master_pid

Leave Supervisor管理python web服务 / 网络研习社#88 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #cn posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang