本文参考:https://code.luasoftware.com/tutorials/nginx/setup-nginx-and-uwsgi-for-flask-on-ubuntu/
因产品后台服务选择Flask+Nginx作为RestfulAPI架构,在ubuntu下进行实地部署。
安装python3
apt-get update
apt-get install python3-pip python3-dev
安装完后,通过python --version 查看。
如果发现系统默认版本为python2,则必须要切换,否则影响virtualenv的安装。
Create a directory for flask app. 在home/目录下
mkdir /home/stockfilter-backend
cd /home/stockfilter-backend
Create requirements.txt
with the following content. 我采用最新版本1.1.1
# Latest version: https://pypi.python.org/pypi/Flask
Flask==1.1.1
Install virtualenv
, create a virtualenv named env
and activate it.
sudo -H pip install virtualenv
virtualenv env
source env/bin/activate
Install flask
and dependencies into lib
directory.
pip install -t lib -r requirements.txt
Deactivate env
.
deactivate
Make a directory to create flask application within stockfilter-backend
directory.
mkdir stockfilter
cd stockfilter
Create python file stockfilter.py
within stockfilter-backend
directory.
import os
import sys
# import libraries in lib directory
base_path = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(base_path, 'lib'))
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello'
Create python file run.py
.
from stockfilter import app
if __name__ == '__main__':
app.run()
sudo -H pip install uwsgi
Check if uwsgi
is available.
uwsgi --version
Test using uwsgi
to serve the flask app. Make sure the execute this within stockfilter-backend
directory.
uwsgi --socket 0.0.0.0:9090 --protocol=http -w run:app
Launch another ssh to test if the flask app is accessible.可以看到返回。
curl http://localhost:9090
You can configure uwsgi
service to run as service/daemon using Upstart or Systemd.
sudo vi /etc/systemd/system/emperor.uwsgi.service
We apply Group=www-data
+ RuntimeDirectory=uwsgi
+ RuntimeDirectoryMode=0775
to enable uWGI access to /var/run/uwsgi/
to write socket file.
[Unit]
Description=uWSGI Emperor
After=network.target
[Service]
Group=www-data
ExecStart=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini
# Requires systemd version 211 or newer
RuntimeDirectory=uwsgi
RuntimeDirectoryMode=0775
Restart=always
KillSignal=SIGQUIT
Type=notify
# dont log to syslog, follow logto
# StandardError=syslog
NotifyAccess=all
[Install]
WantedBy=multi-user.target
Create /etc/uwsgi/emperor.ini
as uwsgi
configuration file.
cd etc
sudo mkdir uwsgi
cd uwsgi
sudo vi emperor.ini
[uwsgi]
emperor = /etc/uwsgi/vassals
uid = www-data
gid = www-data
logto = /var/log/uwsgi/emperor.log
logfile-chown = www-data:www-data
Create /etc/uwsgi/vassals/stockfilter.ini
as uwsgi
app configuration file.
mkdir vassals
cd vassals
sudo vi stockfilter.ini
[uwsgi]
chdir = /home/stockfilter-backend
module = run:app
# python env
home = /home/stockfilter-backend/env
# touch this file to reload the app
touch-reload = /home/stockfilter-backend/run.py
# logto = /var/log/uwsgi/myapp.log
req-logger = file:/var/log/uwsgi/stockfilter-request.log
logger = file:/var/log/uwsgi/stockfilter.log
# master with 2 worker process (based on CPU number)
master = true
processes = 2
# use unix socket for integration with nginx
socket = /var/run/uwsgi/stockfilter.sock
chmod-socket = 660
# enable socket cleanup when process stop
vacuum = true
# ensure compatibility with init system
die-on-term = true
Create /var/log/uwsgi/
.
sudo mkdir /var/log/uwsgi/
sudo chown www-data:adm /var/log/uwsgi/
sudo chmod 755 /var/log/uwsgi/
Start uwsgi.
sudo service emperor.uwsgi start
Enable the service (autostart when system boot).
sudo systemctl enable emperor.uwsgi
You can also use the following commands.
systemctl start emperor.uwsgi.service
systemctl status emperor.uwsgi.service
systemctl stop emperor.uwsgi.service
systemctl restart emperor.uwsgi.service
Note: if there are error starting uWSGI, you can check the following logs
sudo tail -f /var/log/syslog
sudo tail -f /var/log/uwsgi/emperor.log
sudo tail -f /var/log/uwsgi/stockfilter.log
Note: you can also configure one service per app in systemd (not using emperor mode).
Install Nginx.
sudo apt-get install nginx
报错,查找原因为 80 端口被占用。
通过 netstat -lnp | grep 0.0.0.0:80 检查发现是服务器上的apache2占用。只好先停止apache2,安装nginx,然后修改nginx的端口为8090。
Test if Nginx is working.
curl http://localhost
Make a copy of default nginx configuration file.
cd /etc/nginx/sites-available
sudo cp default stockfilter
Edit the stockfilter
configuration file.
sudo vi stockfilter
Configurations which require edit are commented as // EDIT:
.
server {
...
// EDIT: remove default_server
listen 8090;
listen [::]:8090;
// EDIT:
server_name [DOMAIN_NAME];
// EDIT:
location / {
# try_files $uri $uri/ =404;
include uwsgi_params;
uwsgi_pass unix:/var/run/uwsgi/stockfilter.sock;
}
}
Enable our new site.
sudo ln -s /etc/nginx/sites-available/stockfilter /etc/nginx/sites-enabled
nginx默认的default配置,可以在sites-enabled 目录下把软连接default删除,这样nginx就不能启动默认的配置了。这样80端口可以在服务器上恢复apache2来使用。
Check if there are any syntax error.
sudo nginx -t
Restart nginx. You can use sudo service nginx restart
as well.
sudo systemctl restart nginx
Test if ngix is serving the Flask up through uWSGI.
curl http://[DOMAIN_NAME]
注意:修改了uwsgi的相关配置之后,一定要重启uswgi服务,否则在nginx端会报错,比如502错误。
在ECS服务器上将安全配置修改,添加8090端口后,在外部访问。
测试访问:http://xx.xx.xx.xx:8090/ 有返回结果,good!
List the application configuration which ufw
understand.
sudo ufw app list
Available applications:
You can choose HTTP or Full (if you plan to enable SSL later)
sudo ufw allow 'Nginx HTTP'
Verify if the changes is successful.
sudo ufw status
Now you can test to access your website from a external browser http://[DOMAIN_NAME]
.