Flask生产环境配置:Gunicorn+Nginx
第一步是安装所有所需要的库。首先安装pip,Python的包管理工具来管理项目所有的第三方库,包括Gunicorn和Nginx。
sudo apt-get update
sudo apt-get install python-pip python-dev nginx
sudo pip install virtualenv
创建python虚拟环境
接下来我们需要来创建一个python的虚拟环境,我们所有的python第三方库都会安装在这个虚拟环境里不会和服务器上的版本发生冲突,在项目的目录下创建。
sudo pip install virtualenv
source myprojectenv/bin/activate
pip install gunicorn flask
创建 WSGI 入口
用 app=Flask() 作为入口
创建一个 systemd unit file
sudo nano /etc/systemd/system/myproject.service
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myproject
Environment="PATH=/home/sammy/myproject/myprojectenv/bin"
ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 manage:app
[Install]
WantedBy=multi-user.target
现在我们可以启动 Gunicorn 服务来访问Flaks项目了!
sudo systemctl start myproject
sudo systemctl enable myproject
sudo systemctl status myproject
stauts命令查看Gunicorn服务是否正常。正常情况下应该显示
output
myproject.service - Gunicorn instance to serve myproject
Loaded: loaded (/etc/systemd/system/myproject.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2018-07-13 14:28:39 UTC; 46s ago
Main PID: 28232 (gunicorn)
Tasks: 4 (limit: 1153)
CGroup: /system.slice/myproject.service
├─28232 /home/sammy/myproject/myprojectenv/bin/python3.6 /home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007
├─28250 /home/sammy/myproject/myprojectenv/bin/python3.6 /home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007
├─28251 /home/sammy/myproject/myprojectenv/bin/python3.6 /home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007
└─28252 /home/sammy/myproject/myprojectenv/bin/python3.6 /home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007
配置 nginx to proxy requests
sudo nano /etc/nginx/sites-available/myproject
server {
listen 80;
server_name server_domain_or_IP;
location / {
include proxy_params;
proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
}
}
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
检查 niginx 状态然后重启
sudo nginx -t
sudo systemctl restart nginx
部署完成
tips:
- 注意开放服务器的端口
- 注意项目目录下project.sock权限 应该为 777
- sudo systemctl start / restart / stop nginx :Nginx服务器命令
- 注意项目复制到linux服务器后不能复制venv文件夹必须重新建立虚拟环境并安装python包