安装python3环境:
https://blog.csdn.net/bz0446/article/details/105500585
通过pip安装virtualenv:
pip install virtualenv==16.7.10
安装Nginx:
sudo apt install nginx
创建Web目录:
sudo mkdir /var/www/myweb
创建与进入虚拟环境:
进入目录:cd /var/www/myweb
创建虚拟环境:virtualenv --no-site-packages venv
运行虚拟环境:source venv/bin/activate
退出虚拟环境:deactivate
通过git或上传方式将源代码上传至/var/www/myweb后通过pip批量安装所需依赖包:
pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
安装gunicorn:
pip install gunicorn
修改下Flask入口文件代码(在app.run上面增加2行代码):
if __name__ == '__main__':
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
app.run()
启动:
gunicorn 入口文件名:app
或
gunicorn -w 4 -b 127.0.0.1:8000 入口文件名:app
测试:
curl http://127.0.0.1:8000/leilei
如返回正常结果证明启动成功.
备份Nginx配置文件:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak
进入配置文档目录:
cd /etc/nginx/sites-available/
修改Nginx配置文件:
sudo nano ./default
server {
listen 80;
server_name www.****.com; # 这是HOST机器的外部域名,用地址也行
location / {
proxy_pass http://127.0.0.1:8000; # 这里是指向 gunicorn host 的服务地址
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
这样启动之后80端口就可以转发到8000端口了
检查配置:
nginx -t
若出现一下内容,则表示配置成功:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重启Nginx:
重启:sudo service nginx restart
停止:sudo service nginx stop
启动:sudo service nginx start
使用Systemd管理Gunicorn:
sudo nano /etc/systemd/system/python_web_app.service
[Unit]
Description=Gunicorn instance to serve the falcon application
After=network.target
[Service]
User=root
Group=www-data
Environment=/var/www/myweb/venv/bin
WorkingDirectory=/var/www/myweb/
ExecStart=/var/www/myweb/venv/bin/gunicorn -w 4 -b localhost:8000 main:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target
保存文件,关闭编辑器,然后启动新服务:
sudo systemctl start python_web_app
然后启用此服务,以便每次服务器启动时,Gunicorn都会开始为Web应用程序提供服务:
sudo systemctl enable python_web_app
如果更新了源代码,需执行以下命令使新的源代码生效:
sudo systemctl restart python_web_app
补充:
查看Gunicorn运行状态:
pstree -ap|grep gunicorn
出现以上内容,可以看到,其中561为主进程号,使用以下命令,重启Gunicorn。
kill -HUP 561