阿里云部署Flask+uWSGI+Nginx过程

Aug 26 2017

服务器: Ubuntu 16.04 64位

准备工作

首先安装项目所需的组件:pip,dev,nginx。python2下安装

1
2
sudo apt-get update
sudo apt-get install python-pip python-dev nginx

python3

1
2
sudo apt-get update
sudo apt-get install python3-pip python3-dev nginx

安装python虚拟环境

virtualenv 是一个创建隔绝的Python环境的 工具。virtualenv创建一个包含所有必要的可执行文件的文件夹,用来使用Python工程所需的包。
同样,python2下是

1
sudo pip install virtualenv

python3

1
sudo pip3 install virtualenv

在/home目录下创建项目

1
2
3
cd /home
mkdir myproject
cd myproject

在myproject下创建虚拟环境myprojectenv

1
virtualenv myprojectenv

进入虚拟环境

1
source myprojectenv/bin/activate

此时出现 (myprojectenv) root@:/home/myproject#表明已进入虚拟环境

配置Flask应用

安装 Flask and uWSGI

1
pip install uwsgi flask

创建一个Hello world

1
nano ~/myproject/myproject.py

myproject.py

1
2
3
4
5
6
7
8
9
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
app.run(host='0.0.0.0')

配置WSGI

创建一个wsgi.py

1
nano ~/myproject/wsgi.py
1
2
3
4
from myproject import app

if __name__ == "__main__":
app.run()

退出虚拟环境

1
deactivate

创建uWSGI配置文件myproject.ini

1
nano ~/myproject/myproject.ini
1
2
3
4
5
6
7
8
9
10
11
12
[uwsgi]
module = wsgi:app
daemonize = /var/log/uwsgi.log

master = true
processes = 5

socket = myproject.sock
chmod-socket = 666
vacuum = true

die-on-term = true

配置systemd

创建myproject.service

1
sudo nano /etc/systemd/system/myproject.service
1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/home/myproject
Environment="PATH=/home/myproject/myprojectenv/bin"
ExecStart=/home/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

[Install]
WantedBy=multi-user.target

现在可以启动uWSGI服务

1
2
sudo systemctl start myproject
sudo systemctl enable myproject

配置Nginx代理

1
sudo nano /etc/nginx/sites-available/myproject
1
2
3
4
5
6
7
8
9
server {
listen 80;
server_name 服务器IP;

location / {
include uwsgi_params;
uwsgi_pass unix:/home/myproject/myproject.sock;
}
}

开启创建的Nginx服务

1
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

检查Nginx配置是否有错误

1
sudo nginx -t

重启Nginx

1
sudo systemctl restart nginx
1
sudo ufw allow 'Nginx Full'

到此,访问http://server_domain_or_IP
就能出现Hello World了