Home > Operation and Maintenance > Nginx > How to use Nginx to deploy flask application in centos

How to use Nginx to deploy flask application in centos

WBOY
Release: 2023-05-21 22:13:04
forward
1189 people have browsed it

Environment preparation

Python package installation tool pip: sudo apt-get install pip
virtualenv: In order to avoid conflicts between the system environment and the application environment Conflict, use a virtual environment to install application dependencies. virtualenv can create an independent development environment for each python application. Installation method: sudo pip install virtualenv

Virtual environment usage

flask project address:/usr/local/flasky, you only need to run the command under the project address:

virtualenv venv
Copy after login

It is a common convention to use "venv" as the name of the virtual environment, so that we A virtual environment folder venv is created as shown in the red box in the figure below:

How to use Nginx to deploy flask application in centos

Next, activate the virtual environment with just the command

source venv/bin/activate
Copy after login

How to use Nginx to deploy flask application in centos

After activating the virtual environment, there will be a (venv) logo in the command line header. After only the virtual environment is required, all operations to install python will install the packages and references in the virtual environment and will not affect the global situation. The python environment

Instructions to exit the virtual environment, directly type:

deactivate

to exit the virtual environment

Configuring the flask application environment

When developing a flask application, a lot of templates will be applied. "Dog Book" introduces a more convenient way to directly add the flask dependencies of the development environment, etc. It is very convenient to export it as a txt file, and then use the corresponding instructions in the centos virtual environment to install according to this txt file.

pip freeze >requerements.txt
Copy after login

This command exports a text file named requirements.txt. The content is as shown in the figure below

How to use Nginx to deploy flask application in centos

Then use the following command in centos

pip install -r requerments.txt

This will install a copy in the virtual environment that is consistent with the development environment.
Be sure to use batch installation instructions in the virtual environment, otherwise it will be installed globally, and the consequences will be quite painful.

Installing uwsgi

There are not many choices for the actual production operating environment of flask. The more mature ones are [gunicorn] and [uwsgi]. Here is a book recommended by Dong Weiming. These two deployments are discussed in "Python Web Development Practical Combat".

The following content comes from Baidu Encyclopedia:

uwsgi is a web server that implements wsgi protocol, uwsgi, http and other protocols. The function of httpuwsgimodule in nginx is to exchange with uwsgi server. wsgi is a web server gateway interface. It is a specification for communication between a web server (such as nginx, uwsgi, etc.) and a web application (such as a program written with the Flask framework).
The installation instructions are as follows. Please make sure you have entered the virtual environment and activated it:

pip install uwsgi

There is no need to use sudo because virtualvenv has no permission requirements. .

Upload project files

The Linux connection tool used by the blogger is xshell. In a previous article, I talked about how to upload files to the Linux host, so I won’t do it here. Detailed description, show the general project structure and startup file manage.py

How to use Nginx to deploy flask application in centos

The tree command can display the file structure in the form of a tree diagram, and can give the depth of the parameter setting tree , here the blogger shows the 2-layer
installation command:

sudo apt-get install tree

manage.py code is as follows

#coding=utf-8
#!/usr/local/flasky/venv python
'''
created on 2017/11/9
@author: savitar丶
project:
'''
import os
from app import create_app
from flask_script import manager, shell
app = create_app(os.getenv('flask_config') or 'default')
manager = manager(app)

def make_shell_context():
 return dict(app=app)
manager.add_command("shell", shell(make_context=make_shell_context))
@manager.command
def deploy():
 """run deployment tasks."""
 pass
if __name__ == '__main__':
 manager.run()
 #app.run()
Copy after login

Command line running flask project

python manage.py runserver

The above commands are generally used when debugging in the development environment, or commented Remove "manager.run()" and use "app.run()". The latter can directly execute the project in pycharm. I will not explain it in detail here

Configuring uwsgi

We create a new file "config.ini" directly under the root directory of flask, and use the configuration startup method. The content of the file is as follows

[uwsgi]

# uwsgi 启动时所使用的地址与端口

socket = 127.0.0.1:5000

#虚拟环境目录 
home = /usr/local/flasky/venv

#指向网站根目录
chdir = /usr/local/flasky

#python启动程序文件
wsgi-file = manage.py

#python程序内用于启动的application变量名
callable = app

#处理器数
processes = 4

#线程数
threads = 2

#状态监测地址
stats = 127.0.0.1:9191

#设置uwsgi包解析的内部缓存区大小。默认4k

buffer-size = 32768
Copy after login

To execute the configuration file, enter the command on the command line:

uwsgi config.ini

Or do not write the configuration file (not It is recommended to do this), directly enter

uwsgi –socket 127.0.0.1:5000 –wsgi-file manage.py –callable app –process 4 –threads 2

callable=app here This app is a variable in the manage.py program file. The type of this variable is the application class of flask

How to use Nginx to deploy flask application in centos

这里是因为博主已经配置好了项目自启动,已经有一个配置文件在运行了,大家按照正常流程配置就好。ctrl+c关闭程序,在实际项目中我们的服务器上可能会有多个项目在运行,我们需要应用随同服务器启动并作为后台服务运行才是实际项目需要,所以我们需要安装另一个工具来引导执行uwsgi

安装supervisor

supervisor可以同时启动多个应用,最重要的是当某个应用down掉的时候,他可以自动重启该应用,保证可用性。

sudo apt-get install supervisor

supervisor的全局配置文件在

How to use Nginx to deploy flask application in centos

打开该默认配置文件,最下面一行我们看到,该默认配置文件会从 /etc/supervisord/目录下面加载所有的配置文件

How to use Nginx to deploy flask application in centos

我们不需要修改默认的配置文件,只需要在/etc/supervisord/目录下新建一个配置文件(命名为flask_supervisor.conf)
How to use Nginx to deploy flask application in centos

该文件内容如下:

[program:flasky]
# 启动命令入口
command=/usr/local/flasky/venv/bin/uwsgi /usr/local/flasky/config.ini

# 命令程序所在目录
directory=/usr/local/flasky
#运行命令的用户名
user=root

autostart=true
autorestart=true
#日志地址
stdout_logfile=/usr/local/flasky/logs/uwsgi_super.log
Copy after login

这里command这一行代码看起来很长,其实就是之前我们的 “uwsgi config.ini”指令,这里使用的是绝对路径,保证命令和文件的准确性,大家也可以copy这一行代码出去执行,结果是ok的。autostart和autorestart参数保证了我们的应用可以一直保持启动的状态,即使是down掉了也能重启服务。

启动服务

sudo service supervisor start

终止服务

sudo service supervisor stop

安装nginx

nginx是轻量级,性能强,占用资源少,能很好的处理高并发的反向代理软件。

正向代理和反向代理

正向代理,作为一个媒介将互联网上获取的资源返回给相关联的客户端。代理和客户端在一个局域网,对于服务是透明的。反向代理,根据客户端的请求,从后端的服务器上获取资源,然后再讲这些资源返回给客户端。代理和服务器再一个局域网,对客户端是透明的。nginx是反向代理的最佳选择。

反向代理的作用

提高动态语言的io处理能力
加密和ssl加速
安全。
负载均衡
缓存静态内容
支持压缩。

nginx安装指令:

sudo apt-get install nginx

配置nginx

我们找到nginx的配置文件,不要修改默认的nginx.conf(路径 /etc/nginx/nginx.conf)文件,只需要在同样的文件夹下面新建一个文件夹(conf.d)然后在conf.d下面新建配置文件(flask_ng.conf)即可,如下图

How to use Nginx to deploy flask application in centos

flask_ng.conf文件内容如下

server {
  listen 80;
  server_name www.cloud-test.com; #公网地址

  location / {
  include  uwsgi_params;
  uwsgi_pass 127.0.0.1:5000; # 指向uwsgi 所应用的内部地址,所有请求将转发给uwsgi 处理
  uwsgi_param uwsgi_pyhome /usr/local/flasky/venv; # 指向虚拟环境目录
  uwsgi_param uwsgi_chdir /usr/local/flasky; # 指向网站根目录
  uwsgi_param uwsgi_script manage:app; # 指定启动程序
  }
 }
Copy after login

启动nginx

sudo service nginx restart

然后浏览器直接访问服务器http://www.cloud-test.com地址,结果如下

How to use Nginx to deploy flask application in centos 

小case,解决办法,直接修改本机hosts,绑定就好了,如下图所示

How to use Nginx to deploy flask application in centos 

然后再去访问

How to use Nginx to deploy flask application in centos 

然后也可以找自己的同事一起访问,看看并发请求,网站的运行情况,想来能解决在开发环境使用了host 0.0.0.0 也只能处理一个用户的请求的问题

查看应用的运行情况

supervisorctl 是 supervisord 的命令行客户端工具,使用的配置和 supervisord 一样,这里就不再说了。下面,主要介绍 supervisorctl 操作的常用命令:
输入命令 supervisorctl 进入 supervisorctl 的 shell 交互界面(还是纯命令行),可以看到应用的运行情况
就可以在下面输入命令了。:

help # 查看帮助
status # 查看程序状态
stop program_name # 关闭 指定的程序
start program_name # 启动 指定的程序
restart program_name # 重启 指定的程序
tail -f program_name # 查看 该程序的日志
update # 重启配置文件修改过的程序(修改了配置,通过这个命令加载新的配置)

You can also operate directly through shell commands:

supervisorctl status
supervisorctl update

How to use Nginx to deploy flask application in centos

The above is the detailed content of How to use Nginx to deploy flask application in centos. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template