系统版本:centos7.6

安装Flask

虚拟环境是为了方便管理不同项目的开发环境,在python2中需要安装创建虚拟环境的包virtualenv,在python3中自带的有venv包,可以不安装virtualenv。个人建议安装virtualenv,使用virtuallenv构建虚拟环境,因为使用venv创建虚拟环境,运行时可能出现未知的问题。

  1. #python2中安装虚拟环境
  2. pip2 install virtualenv
  3. #python2中创建虚拟环境
  4. virtualenv test-env
  5. ########################################################
  6. cd /opt
  7. #python3中创建虚拟环境
  8. python3 -m venv venv
  9. venv即是创建的虚拟环境,也是一个目录。
  10. #进入虚拟环境
  11. source /opt/venv/bin/activate
  12. #退出虚拟环境使用
  13. deactivate
  14. #建立安装依赖文件
  15. vim requirements.txt
  16. #文件内容如下
  17. Flask==1.0.2
  18. Flask-Script==2.0.6
  19. Flask-SQLAlchemy==2.3.2
  20. PyMySQL==0.9.3
  21. gunicorn==19.7.1
  22. #根据requirements.txt文件安装依赖包
  23. pip3 install -r requirements.txt

Gunicorn使用

  1. #在虚拟环境中安装gunicorn
  2. pip install gunicorn
  3. # 查看帮助
  4. gunicorn -h
  5. # 查看版本
  6. gunicorn -v
  7. # 命令启动程序(Flask代码见2.3),test是主程序的文件名(没有.py),app对应test.py中“app = Flask(__name__)”的app
  8. gunicorn -w 2 -b 127.0.0.1:5000 test:app
  9. #在项目目录中启动程序
  10. gunicorn -w 2 -b 192.168.0.218:8000 app:app -D

gunicorn的参数

  1. -c CONFIG, --config=CONFIG # 设定配置文件。
  2. -b BIND, --bind=BIND # 设定服务需要绑定的端口。建议使用HOST:PORT。
  3. -w WORKERS, --workers=WORKERS # 设置工作进程数。建议服务器每一个核心可以设置2-4个。
  4. -k MODULE # 选定异步工作方式使用的模块。
  5. -D --daemon #后台运行,默认False
  6. preload #显示详细的错误信息

结束进程

  1. [root@SH1 nginx]# ps -ef | grep gunicorn
  2. root 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 -D
  3. root 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 -D
  4. root 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 -D
  5. root 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 -D
  6. root 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 -D
  7. root 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
  8. [root@SH1 nginx]# kill -9 1634
  9. [root@SH1 nginx]# ps -ef | grep gunicorn

安装nginx

  1. #安装nginx
  2. yum install -y nginx
  3. #修改
  4. vim /etc/nginx/nginx.conf
  5. #或者修改,并把/etc/nginx/nginx.conf中server注释掉,否则又会冲突
  6. vim /etc/nginx/conf.d/nginx.conf
  7. server {
  8. listen 80;
  9. server_name default_server;
  10. location / {
  11. proxy_set_header Host $http_host;
  12. proxy_set_header X-Real-IP $remote_addr;
  13. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  14. proxy_set_header X-Forwarded-Proto $scheme;
  15. proxy_pass http://127.0.0.1:8000;
  16. }
  17. }

项目更改后的重新部署

  1. #需要重启gunicorn:首先找到gunicorn的进程号
  2. pstree -ap|grep gunicorn
  3. #根据找到的主进程号,重启gunicorn:
  4. kill -HUP *****
  5. //也可以kill主进程后,用下面的命令重新部署
  6. gunicorn -w 5 -b 127.0.0.1:5000 manage:app -D