问题解决笔记 -- 在 Ubuntu 16 上使用 Nginx 部署 Flask 应用

来源:互联网 发布:mac手势 切换 编辑:程序博客网 时间:2024/06/13 21:59

英文原文:Serving Flask With Nginx

文章的翻译链接 在 Ubuntu 上使用 Nginx 部署 Flask 应用

为了搭载一个restful服务框架的服务器后端,于是决定用flask框架
文章用的环境是Ubuntu 13,但用ubuntu16在最后一步却出现了问题,先来看看每步的作用

1. 安装一些前提软件。当然是用Python
virtualenv:为了满足不同Python应用程序需要不同的应用包,每个应用需要一套独立的 python运行环境 
pip: 用来安装Python模块或包
flask: python Web 应用框架
Nginx: 提供静态文件访问的web服务。可按照预定规则过滤url以及URL的重定向;可作为软负载提供负载均衡服务等等
uWSGI: 由于Nginx不能直接执行托管Python应用程序,所以需要安装uWSGI


2.以上一些软件都可以用pip来安装 ,如 pip install nginx 
在Ubuntu上也可用sudo apt-get install python-nginx 指令来安装
两者的不同在于pip可以安装旧版依赖包,由于apt-get使用了国内的镜像,apt-get的访问速度比pip快不少

注:要更改apt-get  的更新源,可以编辑/etc/apt/sources.list,找相应的国内镜像替换

3.Nginx与网关uWSGI的通信 
include uwsgi_params;
uwsgi_pass unix:/var/www/demoapp/demoapp_uwsgi.sock;
可见是通过demoapp_uwsgi.sock文件连接的

4. Ubuntu 16 下启动uWSGI -- 创建systemd单元文件
当用指令 sudo service uwsgi start 启动uwsgi时
会出现Failed to start uwsgi.service: Unit uwsgi.service not found.
原因在于 Ubuntu 16 不能使用upstart,用systemd
创建systemd单元文件将允许Ubuntu的init系统自动启动uWSGI
将emperor upstart 配置文件/etc/init/uwsgi.conf 删除
创建一个emperor systemd 配置文件 /etc/systemd/system/uwsgi.service

[Unit]Description=uWSGI Emperor serviceAfter=syslog.target[Service]ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sitesRestart=alwaysKillSignal=SIGQUITType=notifyStandardError=syslogNotifyAccess=all[Install]WantedBy=multi-user.target

由于上面配置文件 uwsgi配置目录为/etc/uwsgi/sites
最后 将 uWSGI配置文件/var/www/demoapp/demoapp_uwsgi.ini 软链接到 /etc/uwsgi/sites/demoapp.ini ,文件名根据自己创建的命名

更新,启动,重启后也能启动,键入以下命令
sudo systemctl daemon-reload
sudo systemctl start uwsgi
sudo systemctl enable uwsgi
记得重启下nginx 
sudo /etc/init.d/nginx restart
5. 可能存在的问题
要打开端口5000时,键入以下命令sudo ufw allow 5000

0 0
原创粉丝点击