安装Flask
虚拟环境是为了方便管理不同项目的开发环境,在python2中需要安装创建虚拟环境的包virtualenv,在python3中自带的有venv包,可以不安装virtualenv。个人建议安装virtualenv,使用virtuallenv构建虚拟环境,因为使用venv创建虚拟环境,运行时可能出现未知的问题。
#python2中安装虚拟环境pip2 install virtualenv#python2中创建虚拟环境virtualenv test-env########################################################cd /opt#python3中创建虚拟环境python3 -m venv venvvenv即是创建的虚拟环境,也是一个目录。#进入虚拟环境source /opt/venv/bin/activate#退出虚拟环境使用deactivate#建立安装依赖文件vim requirements.txt#文件内容如下Flask==1.0.2Flask-Script==2.0.6Flask-SQLAlchemy==2.3.2PyMySQL==0.9.3gunicorn==19.7.1#根据requirements.txt文件安装依赖包pip3 install -r requirements.txt
Gunicorn使用
#在虚拟环境中安装gunicornpip install gunicorn# 查看帮助gunicorn -h# 查看版本gunicorn -v# 命令启动程序(Flask代码见2.3),test是主程序的文件名(没有.py),app对应test.py中“app = Flask(__name__)”的appgunicorn -w 2 -b 127.0.0.1:5000 test:app#在项目目录中启动程序gunicorn -w 2 -b 192.168.0.218:8000 app:app -D
gunicorn的参数
-c CONFIG, --config=CONFIG # 设定配置文件。-b BIND, --bind=BIND # 设定服务需要绑定的端口。建议使用HOST:PORT。-w WORKERS, --workers=WORKERS # 设置工作进程数。建议服务器每一个核心可以设置2-4个。-k MODULE # 选定异步工作方式使用的模块。-D --daemon #后台运行,默认False–preload #显示详细的错误信息
结束进程
[root@SH1 nginx]# ps -ef | grep gunicornroot 1578 1 0 14:53 ? 00:00:00 /opt/venv/bin/python3 /opt/venv/bin/gunicorn -w 2 -b 192.168.0.218:8000 app:app -Droot 1634 1 0 14:55 ? 00:00:00 /opt/venv/bin/python3 /opt/venv/bin/gunicorn -w 2 -b 192.168.0.218:8000 app:app -Droot 1636 1634 0 14:55 ? 00:00:00 /opt/venv/bin/python3 /opt/venv/bin/gunicorn -w 2 -b 192.168.0.218:8000 app:app -Droot 1695 1634 0 14:59 ? 00:00:00 /opt/venv/bin/python3 /opt/venv/bin/gunicorn -w 2 -b 192.168.0.218:8000 app:app -Droot 2023 1578 0 16:38 ? 00:00:00 /opt/venv/bin/python3 /opt/venv/bin/gunicorn -w 2 -b 192.168.0.218:8000 app:app -Droot 2024 1578 0 16:38 ? 00:00:00 /opt/venv/bin/python3 /opt/venv/bin/gunicorn -w 2 -b 192.168.0.218:8000 app:app -D[root@SH1 nginx]# kill -9 1634[root@SH1 nginx]# ps -ef | grep gunicorn
安装nginx
#安装nginxyum install -y nginx#修改vim /etc/nginx/nginx.conf#或者修改,并把/etc/nginx/nginx.conf中server注释掉,否则又会冲突vim /etc/nginx/conf.d/nginx.confserver {listen 80;server_name default_server;location / {proxy_set_header Host $http_host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_pass http://127.0.0.1:8000;}}
项目更改后的重新部署
#需要重启gunicorn:首先找到gunicorn的进程号pstree -ap|grep gunicorn#根据找到的主进程号,重启gunicorn:kill -HUP *****//也可以kill主进程后,用下面的命令重新部署gunicorn -w 5 -b 127.0.0.1:5000 manage:app -D
