您的当前位置:首页正文

Flask+Gunicorn+UpStart+Nginx

来源:华佗小知识

1. Flask

pip install flask

一个flask的hello world程序大约会是这样:

# hello.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!\n"
    
if __name__ == "__main__":
    app.run()

然后执行python hello.py,就可以看到:

  * Running on http://127.0.0.1:5000/

按照默认设置,flask在localhost的5000端口跑起来了。

测试flask

另起一个终端。
首先netstat -anp | grep 5000,可以看到输出:

tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      13082/python 

localhost的5000端口被一个pid为13082的python程序占用了。

hello

同时,之前跑着hello.py的终端有输出:

127.0.0.1 - - [16/Mar/2015 15:21:07] "GET / HTTP/1.1" 200 -

测试成功,so easy!

2. Gunicorn

pip install gunicorn
[2015-03-15 12:18:37 +0000] [5710] [INFO] Starting gunicorn 19.2.1
[2015-03-15 12:18:37 +0000] [5710] [INFO] Listening at: http://127.0.0.1:8000 (5710)
[2015-03-15 12:18:37 +0000] [5710] [INFO] Using worker: sync
[2015-03-15 12:18:37 +0000] [5715] [INFO] Booting worker with pid: 5715

按照默认设置,gunicorn在localhost的8000端口跑起来了。

测试gunicorn

和测试Flask一样,curl即可

3. UpStart

description "hello world by gunicorn and flask"

start on (filesystem)
stop on runlevel [016]

respawn
setuid flask # 指定进程的uid
setgid flask # 指定进程的gid
chdir /home/flask/test # 指令被执行的目录

exec gunicorn hello:app

稍微解释一下,这里有一个名叫flask的用户,我们用这个用户来跑gunicorn。然后执行指令的目录为/home/flask/test,也就是hello.py所在的目录。

运行并测试UpStart守护的gunicorn

执行sudo start hello运行job,可以看到:

hello start/running, process 13929

然后ps -up 13929,可以看到:

USER     PID    %CPU %MEM  VSZ   RSS   TTY      STAT START   TIME COMMAND
flask    13929  0.1  2.5   56816 12616 ?        Ss   14:49   0:00 /usr/bin/python /usr/local/bin/gunicorn hello:app

已然在跑了。同样可以curl测试。
另外管理job可以用以下指令:

start hello  # 启动job hello
status hello # 查看job hello的状态
stop hello   # 停止job hello

Nginx

sudo apt-get install nginx

nginx的默认配置文件是/etc/nginx/nginx.conf,其中有2行值得注意:

71: include /etc/nginx/conf.d/*.conf;  
72: include /etc/nginx/sites-enabled/*;

意思是还会从这2个地方include别的配置文件。
可以观察到在/etc/nginx/sites-enabled/下,有一个叫做default的软链接,指向/etc/nginx/sites-available/default。此时若启动nginx,就会使用这个配置文件。

# /etc/nginx/sites-available/blog
server {
    listen 80;
    server_name blog.hezj.xyz;
    access_log /var/log/nginx/blog.access.log;

    location / {
         proxy_pass http://127.0.0.1:8000;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
   location /static/ {
         alias /home/flask/blog/app/static/;
   }
}

将这个文件在/etc/nginx/sites-enabled/下做一个同名的软链接,同时删除掉/etc/nginx/sites-enabled/default,然后执行sudo service nginx restart重启nginx。

测试nginx

此时已然大功告成,nginx监听着80端口,只需要从公网ip访问服务器,即可得到hello world页面。