centos7.0 use Nginx Deployment flask Application Tutorials

Source: Internet
Author: User
Tags to domain virtual environment virtualenv

Reference Blog: Http://www.cnblogs.com/Ray-liang/p/4173923.html?utm_source=tuicool
Modification instructions: Modify the Nginx configuration section, replace the configuration file content and path; switch from IP access to domain name preface

Recently, bloggers are developing a small project The development environment of this machine is python3.6, because of the need to deploy to the server (python2.7) relationship, so studied that most of the online tutorials are deployed on Ubuntu, the blogger is using centos7.0, most of the deployment is actually similar, this blog post for the complete novice may be helpful , and can be described in some of the confusion encountered. Environmental Preparedness

Python Package Installation tool pip: sudo apt-get install pip
Virtualenv: To avoid conflicts between the system environment and the application environment, use the virtual environment to install the application dependencies, virtualenv can create a separate development environment for each Python application, installed by:sudo pip install Virtualenv Virtual Environment use

Flask Project Address:/usr/local/flasky, just run the command at the project address:

virtualenv venv

Conventions generally use "venv" as the name of the virtual environment, so that we create a virtual Environment folder venv as shown in the following figure red Box:

Next, activate the virtual environment, using only instructions

Source Venv/bin/activate


After activating the virtual environment, the command line header will have a (venv) identity, and only after the virtual environment, all the operations that install Python are packed and referenced in a virtual environment without affecting the global Python environment
Exit the virtual environment's instructions, knocking directly:

Deactivate
You can exit the virtual environment configuration Flask Application Environment

Flask application development, will be applied to a very many templates, " Dog book " in the introduction of a more convenient way, directly to the development of the environment of the flask dependence, such as the export of a TXT file, Then use the corresponding instruction in the CentOS virtual environment according to this TXT file installation will be very convenient.

pip Freeze >requerements.txt
This directive exports a file named Requirements.txt text, which is shown in the following image

The following instructions are then used in CentOS
pip Install-r requerments.txt
This will install a replica that is consistent with the development environment in the virtual environment.

note must be in the virtual environment to use the bulk installation instructions, or install to the global go, the consequences of the comparison of eggs pain. Install Uwsgi

Flask actual production Operation Environment choice is not many, more mature is "Gunicorn" and "Uwsgi", here recommended a book Dong Weiming "Python Web Development Combat " Inside there are speaking of these two deployments.
The following content from Baidu Encyclopedia :

UWSGI is a Web server that implements protocols such as WSGI Protocol, UWSGI, HTTP, and so on. The role of Httpuwsgimodule in Nginx is to exchange with the UWSGI server. WSGI is a Web server gateway interface. It is a specification for a Web server (such as a NGINX,UWSGI server) to communicate with Web applications such as programs written with the Flask framework.

Installation instructions are as follows, be sure to ensure that you have entered the virtual environment and activated:

pip Install Uwsgi
You do not need to use sudo because virtualvenv does not have permission requirements. Uploading project Files

The Linux connection tool used by bloggers is Xshell, in a previous blog post http://blog.csdn.net/qq_14908027/article/details/77644353 about how to upload files to a Linux host, This is no longer detailed, show the approximate project structure and startup file manage.py

Tree command can display the file structure in the form of trees, can give the parameter to set the depth of the tree, here the blogger shows 2 layers
Install Command:

sudo apt-get install tree

The 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 ()
command line run Flask Project

python manage.py runserver

The above commands are generally used when debugging in the development environment, or comment out "manager.run ()", using "App.run ()", which can directly execute the project in Pycharm, no longer specify the configuration Uwsgi

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

[Uwsgi]

# The address and port socket used when UWSGI started

= 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包解析的内部缓存区大小. Default 4k

buffer-size = 32768

How the configuration file is executed, and the command line enters the directive:

Uwsgi Config.ini

Or do not write the configuration file (not recommended), direct command line input

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

Here's Callable=app This app is a variable in the manage.py program file, the type of the variable is flask application class


This is because the blogger has configured the project since the start, there is already a configuration file running, we follow the normal process configuration. CTRL + C Close the program, in the actual project on our server may have more than one project running, we need to apply with the server to start and run as a background service is the actual project needs, so we need to install another tool to boot execution Uwsgi installation Supervisor

Supervisor can start multiple applications at the same time, most importantly, when an application down, he can automatically restart the application to ensure availability.

sudo apt-get install supervisor

The Supervisor global configuration file is

Open the default profile, and at the bottom of the line we see that the default profile loads all of the profiles from under the /etc/supervisord/ directory

We do not need to modify the default configuration file, just create a new profile (named flask_supervisor.conf) in the /etc/supervisord/ directory.

The contents of the document are as follows:

[Program:flasky]
# Launch Command entry
command=/usr/local/flasky/venv/bin/uwsgi/usr/local/flasky/config.ini

# Command program directory
directory=/ Usr/local/flasky
#运行命令的用户名
user=root

autostart=true
autorestart=true
#日志地址
stdout_ Logfile=/usr/local/flasky/logs/uwsgi_super.log

Here command this line of code looks very long, in fact, before our "Uwsgi config.ini" instructions, where the use of absolute path, to ensure the accuracy of the command and file, 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 remain in a start-up state, even if it is down, it can restart the service. Start a service

sudo service supervisor start Terminate service

sudo service supervisor Stop Install Nginx

Nginx is lightweight, strong performance, less resources, can be very good handling of high concurrency of the reverse agent software. forward agent and reverse proxy

Forward proxy, as a medium to return the resources acquired on the Internet to the associated client. The agent and client are in a local area network that is transparent to the service. The reverse proxy, which obtains resources from the backend server at the request of the client, and then returns the resources to the client. The agent and server are again a LAN, transparent to the client. Nginx is the best choice for reverse proxies. the role of the reverse proxy

Improve IO processing capabilities for dynamic languages
Encryption and SSL acceleration
Safety.
Load Balancing
Caching Static Content
Supports compression.

Nginx Installation Instructions:

sudo apt-get install nginx Configure Nginx

We found Nginx's profile, do not modify the default nginx.conf (path/etc/nginx/nginx.conf) file, just create a new folder under the same folder (CONF.D) and create a new profile under CONF.D (flask _ng.conf) can be, the following figure

The contents of the flask_ng.conf file are as follows

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

      location/{
        include      uwsgi_params;
        Uwsgi_pass   127.0.0.1:5000;  # point to the internal address applied by UWSGI, all requests will be forwarded to UWSGI processing
        uwsgi_param uwsgi_pyhome/usr/local/flasky/venv; # point to Virtual Environment directory
        Uwsgi_param Uwsgi_chdir  /usr/local/flasky; # point to Site root
        uwsgi_param uwsgi_script manage:app; # Specify startup program
      }
    }

start Nginx

sudo service nginx restart
The browser then accesses the server http://www.cloud-test.com address directly, and the results are as follows

Small case, solution, directly modify the local hosts, binding is good, as shown in the following figure

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


Then you can also find your colleagues to visit, see the concurrent request, the site's operation, want to solve in the development environment using the host 0.0.0.0 also can only handle a user's request to see the application of the Operation

Supervisorctl is the Supervisord command-line client tool, using the same configuration as Supervisord, which is no longer mentioned here. The following are mainly about the common commands for SUPERVISORCTL operations:
Enter the command supervisorctl into the Supervisorctl Shell interactive Interface (or a pure command line) to see how the application Works
You can enter the command below. :

Help # View Assistance
Status # View program status
Stop Program_name # closes the specified program
Start Program_name # starts the specified program
Restart Program_name # Restart the specified program
Tail-f program_name # View the log of the program
Update # Reboot Profile modified program (modified configuration, load new configuration via this command)
You can also operate directly through the shell command:

Supervisorctl status
SUPERVISORCTL Update

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.