1. 创建Flask项目文件夹
mkdir Flaskproject
cd Flaskproject
2. 配置Flask源码以及虚拟环境
示例app.py:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)
pip install virtualenv # 如果已安装则跳过
python -m venv flaskenv # 新建flask虚拟环境
source flaskenv/bin/activate # 激活flask虚拟环境(退出虚拟环境:deactivate)
pip install -r requirements.txt # 安装依赖库
# pip install -r requirements.txt --no-dependencies 包版本冲突时可忽略版本要求,解决冲突
# 生成依赖库文件用 pip freeze > requirements.txt
3. 安装gunicorn
pip install gunicorn
4. 启动gunicorn服务
nohup gunicorn -w 4 -b 0.0.0.0:5000 app:app & #不带日志
nohup gunicorn -w 4 -b 0.0.0.0:5000 app:app > gunicorn.log 2>&1 & #带日志
其中-w设置最大进程数,-b绑定IP和端口,第一个app为app.py的文件名,第二个app为Flask应用的实例名,根据自己的项目修改。
如需自定义gunicorn配置文件,可在对应路径下创建conf文件,配置好后在启动命令中加入-c gunicorn.conf即可。(gunicorn的配置教程可参考Gunicorn配置详解)
此时登录http://x.x.x.x:5000就能访问你的Flask项目了。
如果想使用80端口进行访问,则可以通过Ngix将80端口指向你所指定的端口。
5. 安装Nginx
sudo apt-get install nginx
6.修改Nginx配置文件(/etc/nginx/nginx.conf)
找到下面两行,把第二行注释掉。(保存文件可能需要sudo或root权限)
include /etc/nginx/conf.d/*.conf;
#include /etc/nginx/sites-enabled/*;
在http配置中加入server{}配置,注意要加在http{}里面。
http {
##############################
server {
listen 80;
server_name localhost; # 外界实际访问的地址
location / {
proxy_pass http://localhost:5000; # 转发的本机端口地址
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
}
##############################
}
如果有ssl证书,并想http自动重定向到https,则使用以下配置:
http {
##############################
server {
listen 80;
server_name localhost; # 外界实际访问的地址
return 301 https://$host$request_uri; # http重定向https
}
server {
listen 443 ssl;
server_name localhost;
ssl_certificate xxx.com.pem; # 改为自己的ssl证书的目录
ssl_certificate_key xxx.com.key; # 改为自己的ssl证书秘钥的目录
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://localhost:5000; # 转发的本机端口地址
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
}
##############################
}
7. 测试Nginx配置是否正确
$ sudo nginx -tc /etc/nginx/nginx.conf
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
8. 重启Nginx服务
sudo service nginx restart
# 或者 sudo nginx -s reload
此时登录http://x.x.x.x即可直接访问页面,无需指定端口号了。
大家感兴趣也可以看看我的Flask项目,写了几个有趣&有用的小工具。