当前位置:   article > 正文

Ubuntu16.04下部署Nginx+uWSGI+Flask_ubuntu16.04 linux uwsgi+nginx+flask

ubuntu16.04 linux uwsgi+nginx+flask

本文参考:https://code.luasoftware.com/tutorials/nginx/setup-nginx-and-uwsgi-for-flask-on-ubuntu/ 

因产品后台服务选择Flask+Nginx作为RestfulAPI架构,在ubuntu下进行实地部署。

1. 安装Python

安装python3

apt-get update

apt-get install python3-pip python3-dev

安装完后,通过python --version 查看。

如果发现系统默认版本为python2,则必须要切换,否则影响virtualenv的安装。

2. 安装Flask lib

Create a directory for flask app. 在home/目录下

  1. mkdir /home/stockfilter-backend
  2. cd /home/stockfilter-backend

Create requirements.txt with the following content. 我采用最新版本1.1.1

  1. # Latest version: https://pypi.python.org/pypi/Flask
  2. Flask==1.1.1

Install virtualenv, create a virtualenv named env and activate it.

  1. sudo -H pip install virtualenv
  2. virtualenv env
  3. source env/bin/activate

Install flask and dependencies into lib directory.

pip install -t lib -r requirements.txt

Deactivate env.

deactivate

3. Create flask app

Make a directory to create flask application within stockfilter-backend directory.

  1. mkdir stockfilter
  2. cd stockfilter

Create python file stockfilter.py within stockfilter-backend directory.

  1. import os
  2. import sys
  3. # import libraries in lib directory
  4. base_path = os.path.dirname(__file__)
  5. sys.path.insert(0, os.path.join(base_path, 'lib'))
  6. from flask import Flask
  7. app = Flask(__name__)
  8. @app.route('/')
  9. def home():
  10. return 'Hello'

Create python file run.py.

  1. from stockfilter import app
  2. if __name__ == '__main__':
  3. app.run()

4. Install uwsgi

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.

5. Running uWSGI via Systemd (Ubuntu 16.04)

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.

  1. [Unit]
  2. Description=uWSGI Emperor
  3. After=network.target
  4. [Service]
  5. Group=www-data
  6. ExecStart=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini
  7. # Requires systemd version 211 or newer
  8. RuntimeDirectory=uwsgi
  9. RuntimeDirectoryMode=0775
  10. Restart=always
  11. KillSignal=SIGQUIT
  12. Type=notify
  13. # dont log to syslog, follow logto
  14. # StandardError=syslog
  15. NotifyAccess=all
  16. [Install]
  17. WantedBy=multi-user.target

Create /etc/uwsgi/emperor.ini as uwsgi configuration file.

  1. cd etc
  2. sudo mkdir uwsgi
  3. cd uwsgi
  4. sudo vi emperor.ini
  1. [uwsgi]
  2. emperor = /etc/uwsgi/vassals
  3. uid = www-data
  4. gid = www-data
  5. logto = /var/log/uwsgi/emperor.log
  6. logfile-chown = www-data:www-data

6. Create uWSGI app configuration file

Create /etc/uwsgi/vassals/stockfilter.ini as uwsgi app configuration file.

  1. mkdir vassals
  2. cd vassals
  3. sudo vi stockfilter.ini
  1. [uwsgi]
  2. chdir = /home/stockfilter-backend
  3. module = run:app
  4. # python env
  5. home = /home/stockfilter-backend/env
  6. # touch this file to reload the app
  7. touch-reload = /home/stockfilter-backend/run.py
  8. # logto = /var/log/uwsgi/myapp.log
  9. req-logger = file:/var/log/uwsgi/stockfilter-request.log
  10. logger = file:/var/log/uwsgi/stockfilter.log
  11. # master with 2 worker process (based on CPU number)
  12. master = true
  13. processes = 2
  14. # use unix socket for integration with nginx
  15. socket = /var/run/uwsgi/stockfilter.sock
  16. chmod-socket = 660
  17. # enable socket cleanup when process stop
  18. vacuum = true
  19. # ensure compatibility with init system
  20. die-on-term = true

Create /var/log/uwsgi/.

  1. sudo mkdir /var/log/uwsgi/
  2. sudo chown www-data:adm /var/log/uwsgi/
  3. 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.

  1. systemctl start emperor.uwsgi.service
  2. systemctl status emperor.uwsgi.service
  3. systemctl stop emperor.uwsgi.service
  4. 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).

7. Install and Setup Nginx for uWSGI

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.

  1. cd /etc/nginx/sites-available
  2. sudo cp default stockfilter

Edit the stockfilter configuration file.

sudo vi stockfilter

Configurations which require edit are commented as // EDIT:.

  1. server {
  2. ...
  3. // EDIT: remove default_server
  4. listen 8090;
  5. listen [::]:8090;
  6. // EDIT:
  7. server_name [DOMAIN_NAME];
  8. // EDIT:
  9. location / {
  10. # try_files $uri $uri/ =404;
  11. include uwsgi_params;
  12. uwsgi_pass unix:/var/run/uwsgi/stockfilter.sock;
  13. }
  14. }

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!

8. Allow Nginx port for firewall

List the application configuration which ufw understand.

sudo ufw app list

Available applications:

  • Nginx Full (HTTP + HTTPS)
  • Nginx HTTP
  • Nginx HTTPS
  • OpenSSH

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].

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/601225
推荐阅读
相关标签
  

闽ICP备14008679号