当前位置: 首页 > 工具软件 > awesome-ecs > 使用案例 >

阿里云ECS部署Flask(Nginx,gunicorn,supervisor,fabric,ubuntu16.04)

龙亮
2023-12-01

先上网站 http://139.224.235.140/,(域名还没弄好)

一、编写fabric脚本

fabric只支持python2,只需要在开发机子上安装python2,服务器不需要
编写fabric脚本,把flask程序打包并上传到阿里云ECS的ubuntu服务器
针对狗书编写的脚本如下:

# -*- coding: utf-8 -*-
import os, re
from datetime import datetime
from fabric.api import *

env.user='root'
env.password='****'
env.hosts=['112.233.244.255']

_TAR_FILE='huu-flask.tar.gz'

def build():
    includes=['app','config.py','manage.py','requirements.txt']
    excludes=['__pycache__','*.pyc','*.pyo']
    local('rm -f dist/%s'%_TAR_FILE)
    with lcd(os.path.abspath('.')):
        cmd=['tar','--dereference','-czvf','./dist/%s'%_TAR_FILE]
        cmd.extend(includes)
        cmd.extend(['--exclude=\'%s\''% ex for ex in excludes])
        local(' '.join(cmd))

_REMOTE_TMP_TAR='/tmp/%s'%_TAR_FILE
_REMOTE_BASE_DIR='/srv/flasky'
def deploy():
    newdir='flasky-%s'%datetime.now().strftime('%y-%m-%d_%H.%M.%S')
    run('rm -f %s'%_REMOTE_TMP_TAR)
    put('dist/%s'%_TAR_FILE,_REMOTE_TMP_TAR)
    with cd(_REMOTE_BASE_DIR):
        run('mkdir %s'%newdir)
    with cd('%s/%s'%(_REMOTE_BASE_DIR,newdir)):
        run('tar -xzvf %s'%_REMOTE_TMP_TAR)
    with cd(_REMOTE_BASE_DIR):
        run('rm -rf flasky')
        run('ln -s %s flasky'%newdir)

二、用supervisor启动flask程序

首先生成配置:

mkdir /etc/supervisor
echo_supervisord_conf > /etc/supervisor/supervisord.conf

编写配置:

[program:flasky]
command=/srv/venv3/bin/gunicorn manage:app --access-logfile /srv/flasky/flasky/logs/flasky.log
directory=/srv/flasky/flasky
user=root
#用gunicorn启动flask下面这个配置好像不管用,可以在gunicorn启动命令中加入log日志文件
stdout_logfile=/srv/flasky/flasky/logs/flasky.log
environment=A="1",B="2" #可以设置环境变量,虚拟环境添加PATH=""

启动:

supervisord -c /etc/supervisor/supervisord.conf
supervisorctl start flasky

查看状态:
supervisor本身的日志文件在
/tmp/supervisord.log

supervisorctl status

三、配置Nginx

在/etc/nginx/sites-available下有default可以备份后修改

server {
    listen      80; # 监听80端口

    root       /srv/flask/www;

    access_log /srv/flask/log/access_log; #默认在/var/log/nginx 
    error_log  /srv/flask/log/error_log;#默认在/var/log/nginx 

    # server_name awesome.liaoxuefeng.com; # 配置域名

    # 处理静态文件/favicon.ico:
    location /favicon.ico {
        root /srv/flask/www;
    }

    # 处理静态资源:
    location ~ ^\/static\/.*$ {
        root /srv/flask/www;
    }

    # 动态请求转发到9000端口:
    location / {
        proxy_pass       http://127.0.0.1:9000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

最后,
/etc/init.d/nginx reload
就可以查看网站了

 类似资料: