Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deploy flask applications using Nginx in centos 7. 0

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to use centos 7.0 to deploy flask applications using Nginx, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Modification instructions: modify the nginx configuration part, change the content and path of the configuration file; switch from ip access to domain name access

Preface

Recently, the blogger is developing a small project, the native development environment is python3.6, because of the need to deploy to the server (python2.7), so I studied it. Most of the tutorials online are deployed on Ubuntu, bloggers use centos7.0, and most of the deployments are similar. This blog post may be helpful to complete novices and describe some puzzles encountered.

Environmental 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, using virtual environments to install application dependencies, virtualenv can create a separate development environment for each python application, installed by sudo pip install virtualenv

Use of virtual environment

Flask project address: / usr/local/flasky, just run the instruction under the project address:

Virtualenv venv

It is customary to use "venv" as the name of the virtual environment, so we have created a folder for the virtual environment, venv, as shown in the red box below:

Next, activate the virtual environment, using only instructions

Source venv/bin/activate

After activating the virtual environment, the command line header will be marked with (venv). After only the virtual environment, all the operations of installing python will be installed in the virtual environment with packages and references, which will not affect the global python environment.

To exit the virtual environment, directly tap:

Deactivate

You can exit the virtual environment.

Configure the flask application environment

Flask application development, will be applied to a lot of templates, "Dog Book" introduces a more convenient way to directly export the flask dependency of the development environment into a txt file, and then use the corresponding instructions in the centos virtual environment to install according to this txt file will be very convenient.

Pip freeze > requerements.txt

This directive exports the text of a file named requirements.txt with the contents shown in the following figure

Then use the following instructions in centos

Pip install-r requerments.txt

This will install a copy consistent with the development environment in the virtual environment.

Install uWSGI

There are not many choices for the actual production operation environment of flask, and the more mature ones are [Gunicorn] and [uWSGI]. Here we recommend a book, Dong Weiming's "Python Web Development practice", which talks about these two deployments.

The following content is from Baidu encyclopedia:

UWSGI is a Web server, which implements WSGI protocol, uwsgi, http and other protocols. The role of HttpUwsgiModule in Nginx is to exchange with the uWSGI server. WSGI is a Web server gateway interface.

The installation instructions are as follows. Be sure to enter the virtual environment and activate it:

Pip install uwsgi

You do not need to use sudo because virtualvenv has no permission requirements.

Upload project files

The linux connection tool used by bloggers is xshell. In a previous article, https://www.jb51.net/article/130991.htm talked about how to upload files to the linux host. I will not elaborate here, but show the general project structure and launch the file manage.py.

Installation commands:

Sudo apt-get install tree

The manage.py code is as follows

# codingchangesutf8: codingintoflaskyUnivenv python'''Created on 2017/11/9@author: Savitar, Project:'''import osfrom app import create_appfrom flask_script import Manager, Shellapp = 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.commanddef deploy (): "" Run deployment tasks. " Passif _ _ name__ = ='_ main__': manager.run () # app.run ()

Command line to run the flask project

Python manage.py runserver

Configure uWSGI

We create a new file "config.ini" directly under the root directory of flask, using configuration startup. The contents of the document are as follows

[uwsgi] # address and port used for uwsgi startup socket = 127.0.0.1 home 500 virtual environment directory home = / usr/local/flasky/venv# points to the website root directory chdir = / usr/local/flasky#python startup program file wsgi-file = application variable name for startup within the manage.py#python program callable = number of app# processors processes = number of threads threads = "state monitoring address stats = 127.0 .0.1 919 sets the size of the internal cache for uwsgi packet parsing. Default 4kbuffer-size = 32768

How the configuration file is executed, enter instructions on the command line:

Uwsgi config.ini

Or instead of writing the configuration file (not recommended), enter it directly on the command line

Uwsgi-socket 127.0.0.1 wsgi-file manage.py 5000-wsgi-file manage.py-callable app-process 4-threads 2

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

This is because the blogger has configured the project to start itself, and there is already a configuration file running, so just configure it according to the normal process. Ctrl+c shutdown program, in the actual project, there may be multiple projects running on our server, we need to start the application with the server and run as a background service is the actual project need, so we need to install another tool to guide the execution of uwsgi

Install supervisor

Supervisor can launch multiple applications at the same time, and the most important thing is that when an application down falls down, it can automatically restart the application to ensure availability.

Sudo apt-get install supervisor

The global configuration file for supervisor is available in the

Open the default configuration file, and on the bottom line we see that the default configuration file loads all configuration files from the / etc/supervisord/ directory

The contents of the file are as follows:

[program:flasky] # start the command entry command=/usr/local/flasky/venv/bin/uwsgi / usr/local/flasky/config.ini# the directory where the command program is located, the user name of the user=rootautostart=trueautorestart=true# log address of the command running command stdout_logfile=/usr/local/flasky/logs/uwsgi_super.log

Here command this line of code looks very long, in fact, is before our "uwsgi config.ini" instruction, here is the absolute path, to ensure the accuracy of commands and files, we can also copy this line of code out to execute, the result is ok. The autostart and autorestart parameters ensure that our application can always be started, and the service can be restarted even if the down is dropped.

Start the service

Sudo service supervisor start

Termination of service

Sudo service supervisor stop

Install Nginx

Nginx is lightweight, strong performance, occupies less resources, and can well deal with high concurrency reverse proxy software.

Forward proxy and reverse proxy

A forward agent acts as a medium to return resources acquired on the Internet to associated clients. The agent and client are in a local area network and are transparent to the service. Reverse proxy, according to the request of the client, get resources from the back-end server, and then return these resources to the client. The agent and the server are then a local area network, which is transparent to the client. Nginx is the best choice for reverse proxy.

The role of reverse proxy

Improving the IO processing ability of dynamic languages

Encryption and SSL acceleration

It's clear.

Load balancing

Cache static content

Compression is supported.

Nginx installation instructions:

Sudo apt-get install nginx

Configure Nginx

We find the configuration file for nginx. Instead of modifying the default nginx.conf (path / etc/nginx/nginx.conf) file, we just need to create a new folder (conf.d) under the same folder and then create a new configuration file (flask_ng.conf) under conf.d, as shown below.

The content of flask_ng.conf file is as follows

Server {listen 80; server_name www.cloud-test.com; # public network address location / {include uwsgi_params; uwsgi_pass 127.0.0.1 location 5000; # points to the internal address applied by uwsgi, and all requests will be forwarded to uwsgi processing uwsgi_param UWSGI_PYHOME / usr/local/flasky/venv; # to the virtual environment directory uwsgi_param UWSGI_CHDIR / usr/local/flasky # point to the website root directory uwsgi_param UWSGI_SCRIPT manage:app; # specify the launcher}}

Start Nginx

Sudo service nginx restart

Then the browser accesses the server http://www.cloud-test.com address directly, and the result is as follows

Small case, the solution is to modify the native hosts directly and bind it, as shown in the following figure

And then visit http://www.cloud-test.com.

View the operation of the application

Supervisorctl is supervisord's command line client tool, using the same configuration as supervisord, so I won't talk about it here. Next, we mainly introduce the common commands of supervisorctl operation:

You can enter the command below. :

Help # View help

Status # View program status

Stop program_name # closes the specified program

Start program_name # start the specified program

Restart program_name # restart the specified program

Tail-f program_name # View the log of the program

Update # restart the program modified by the configuration file (modified configuration to load the new configuration with this command)

You can also operate directly through the shell command:

Supervisorctl status

Supervisorctl update

These are all the contents of the article "how to deploy flask applications using Nginx in centos 7.0". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report