本文主要介紹如何使用supervisor作爲守護進程管理工具。來部署python項目(服務器ubuntu)
1.python環境安裝(ubuntu系統)
apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools
2.python虛擬環境安裝(ps:假定flask_app是待部署的項目)
cd /your/path/to/flask_app
python3.6 -m venv flask_appenv
source flask_appenv/bin/activate (進入虛擬環境)
deactivate (退出虛擬環境)
pip install flask gunicorn (在虛擬環境中執行)
3.supervisor安裝
pip install supervisor
mkdir -p /etc/supervisor
mkdir -m 755 -p /etc/supervisor/
echo_supervisord_conf > /etc/supervisord.conf
編輯配置文件最後兩行
vim /etc/supervisord.conf
[include]
files = /etc/supervisor/*.conf
4.創建日誌目錄
mkdir -p /var/log/gunicorn
chown -R www-data:www-data /var/log/gunicorn/
5.創建項目配置文件
vim /etc/supervisor/flask_app.conf
[program:flask_app]
directory = /data/backend/idata/flask_app
command = /your/path/to/flask_app/flask_appenv/bin/gunicorn --workers 33 --worker-class gevent --bind unix:flask_app.sock -m 007 app:server
user = www-data
autostart = true
autorestart = true
startretries = 3
redirect_stderr = true
stdout_logfile_maxbytes = 200MB
stdout_logfile_backups = 10
stdout_logfile = /var/log/gunicorn/flask_app.log
workers 數爲cpu核心數 X 2 + 1
user 啓動用戶(www-data:nginx用戶)
redirect_stderr stderr 重定向到 stdout
stdout_logfile_maxbytes 日誌文件大小
stdout_logfile_backups 日誌文件備份數
stdout_logfile 日誌文件
ps:管理supervisord
supervisord -c /etc/supervisord.conf
supervisorctl -c /etc/supervisord.conf status (查看狀態)
supervisorctl -c /etc/supervisord.conf reload(重啓)
ps:項目管理
supervisorctl -c /etc/supervisord.conf stop flask_app
supervisorctl -c /etc/supervisord.conf start flask_app
supervisorctl -c /etc/supervisord.conf restart flask_app
6.啓動項目
supervisorctl -c /etc/supervisord.conf start flask_app
7.配置nginx代理(此處示例爲php+python的項目混合部署)
server {
listen 80;
listen 443 ssl;
server_name xxx.com;
root /php/project/root;
#if ($server_port = 80) {
# return 301 https://$server_name$request_uri;
#}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
location ^~ /openapi/v1/tool/query/run {
include proxy_params;
proxy_pass http://unix:/you/path/to/flask_app/flask_app.sock;
}
access_log /var/log/nginx/flaskapp.cn.access.log main;
}
server {
listen 80;
index index.html index.htm index.nginx-debian.html;
server_name flask.biihu.com.cn;
location / {
include uwsgi_params;
proxy_pass unix:/you/path/to/flask_app/flask_app.sock;
try_files $uri $uri/ =404;
}
}