Flask+uwsgi+nginx+ubuntu Deployment Tutorials

Source: Internet
Author: User
Tags scp command using git virtual environment virtualenv git clone

Learn Flask, write a Flask application need to deploy, just want to toss their own server. According to the tutorial of the search, for the principle of smattering, bumps, as long as the run up, thank goodness and then no longer toss, to the next need to deploy, this process will be repeated. Don't know how many people have arrows in their knees? I have done so, it is really stupid, so I decided to write a Flask+uwsgi+nginx+ubuntu deployment tutorial, answer some of my own in the process of the question, from the principle to the scheme, a small white angle, summed up the deployment, operation and maintenance of this matter, should be for beginners Flask The students who need to be deployed have some help.

Introduction to the Environment Ubuntu

I use the Ubuntu system version is 14.04, using a few Linux distributions, now the first choice of the system is Ubuntu, because Ubuntu has a commercial company Canonical to do development and maintenance, the use of more people, there is a large community support, encountered problems easy to solve. I took a long time of the Linux system, my advice to the novice is, do not waste time on this, should solve the actual problem-oriented, practical point to improve the programming ability. Loading systems, optimizing systems, and remembering all sorts of cool commands are not really helpful for improving your programming skills. So you ask me porcelain not porcelain Ubuntu, I am of course a porcelain, with Ubuntu of course will encounter pits, but compared to other systems will be less, it will be easy to solve a point. In fact, Ubuntu has become the first choice for servers, and the most selected Linux distribution on AWS is Ubuntu. The Linux distribution version of Quora is also Ubuntu, and the founder Adam D ' Angelo explains why in this answer. In general, for no particular reason, Ubuntu should be the first choice, after more experience, if you are interested in a distribution, or want to make some special attempts to jump out of the comfort zone, try other systems also no harm.

Uwsgi

We know that Flask has its own web server, through Werkzeug, we can build WSGI services, run our website, but Flask is a web framework, not a Web server, although Werkzeug is powerful, but only for development, not for production, For the WEB server, we have a more professional choice, that is Uwsgi, Uwsgi is a full-site hosting services, it implements the application server (supporting a variety of programming languages), agents, Process Manager, monitor. The name is UWSGI because it is the first to implement the Python language WSGI.

The UWSGI consists of four parts:

    • UWSGI protocol
    • Web server built-in Support protocol module
    • Application Server protocol Support module
    • Process Control Procedures

Uwsgi is written in C and has high performance.

Recommended Reading

    • Project Home address in here
    • Official documents in this
    • Quick Start
The difference between WSGI, Uwsgi, Uwsgi

What is the specific process when we deploy an application and browse the Web? First we have to have a Web server to handle the contents of the HTTP protocol, the Web server obtains the client's request, gives the application, the application finishes processing, returns to the Web server, and the Web server returns to the client. There is a clear interaction between the Web server and the application, and there are many specifications for the interaction between the Web server and the application, with the first CGI, and then the Fasgcgi,java dedicated Servlet specification for improved CGI performance, the Python-specific WSGI Specifications and so on. With a unified standard, the portability of the program is greatly improved. Here we only introduce WSGI.

WSGI full name is the Web server gateway Interface, which is the Web servers gateways interface, which is a simple and common interface between Web servers and Web applications defined by the Python language , based on the existing CGI standard Design, and later in many other languages there are similar interfaces. In general, WSGI can be divided into two parts of servers and applications, which can actually be understood as a bridge between the server and the application, with the server on one side and the application on the other.

According to the classification of Web Components, WSGI can be divided into three categories, Web applications, Web servers, Web middleware. The part of the application side is implemented through a variety of Web frameworks in the Python language, such as Flask,django, where developers do not have to deal with WSGI, and the framework will help solve them, and developers need to deal with HTTP requests and responses, and the parts of the WEB server will be more complicated. Can be implemented through UWSGI, but also with the most common Web servers, such as Apache, Nginx, but these Web servers do not have a built-in WSGI implementation, is done by extension. such as Apache, through the extension module Mod_wsgi to support Wsgi,nginx can through the proxy way, the request is packaged, to the application server, such as Uwsgi. Uwsgi can complete the service side of WSGI, process management and call to application. WSGI Middleware Part can understand this: we see WSGI as a bridge, the bridge has two piers, one is the application side, the other is the server side, then the bridge deck is WSGI middleware, the middleware has a server, application side two roles, of course, also need to comply with WSGI server and WSGI the restrictions and needs on both sides of the application. More details can be seen in the description of PEP-333 middleware

Flask relies on the Werkzeug is a WSGI toolkit, the official document is defined as Werkzeug is designed for Python http and WSGI utility library. What we need to note is that the Flask comes with Werkzeug for development and not for production environments, Flask is a web framework, and Werkzeug is not a web framework, it's not a Web server, it's just a WSGI toolkit, and its role in Flask is as The underlying library of the WEB framework, which facilitates our development.

We put Uwsgi and Uwsgi together to explain. Uwsgi is a WEB server program, WSGI, mentioned above, is a protocol, UWSGI is also a protocol, UWSGI implementation of UWSGI, WSGI, HTTP and other protocols. Uwsgi's introduction can be seen here, Uwsgi is an own protocol used by UWSGI, which uses 4 bytes to define the transport data type description. Despite all the agreements, Uwsgi and WSGI are not connected, and we need to differentiate these two words.

Nginx

Nginx is an efficient WEB server and reverse proxy server, can be used as load balancer (when there are N users to access the server, can realize the shunt, share the pressure of the server), compared to Apache, nginx support high concurrency, can support millions TCP connection, 100,000 level of concurrent connection, Simple deployment, less memory consumption, low cost, but Nginx modules are not rich in Apache. Nginx Support Uwsgi UWSGI protocol, so we can combine nginx with Uwsgi, nginx by uwsgi_pass the dynamic content to UWSGI processing.

Official documents in this

The best Nginx tutorials in this

The relationship between Uwsgi and Nginx

From the above explanation, we know that UWSGI can play the role of the WEB server, then why is there uwsgi also need Nginx?

The most common argument is that Nginx has a better performance in handling static files. In fact, if it is a small site, no static files need to handle, only with UWSGI is also possible, but with Nginx this layer, the advantages can be very specific:

    1. For the operation is more convenient, if the server is an IP attack, in the Nginx configuration file blacklist Add this IP, if only with Uwsgi, then you need to modify in the code. On the other hand, Nginx is a battle-hardened Web server, in the performance of Uwsgi appear more professional, such as Uwsgi in the earlier version is not support HTTPS, can be said Nginx more secure.

    2. Nginx is characterized by the ability to do load balancing and HTTP caching, if more than one server, Nginx Basic is the necessary option, through nginx, the resources can be allocated to different server nodes, only one server, can also improve performance, because Nginx can be headers Expires or E-tag,gzip compression and other ways to deal with static resources, after all, is written in C, call is native function, for I/O is optimized, for dynamic resources, Nginx can also implement the function of caching, with CDN optimization (this is UWSGI do Less than that). Nginx support Epoll/kqueue and other efficient network library, can handle high concurrent short connection request, performance than uwsgi do not know where to go.

    3. If the server host on the run Php,python and other languages written in a number of applications, you need to listen to 80 ports, this time Nginx is the necessary option. Because we need a forwarding service.

So, Nginx is also the essential option.

Deployment Readiness

Here I assume we've got a brand new server. In general, the Linux system will be preloaded with Python, but not necessarily the Easy_install tool, we can apt-get install python-setuptools install Easy_install, and then install Pip via Easy_install.

Take care of the Python environment
$ sudo apt-get install python-setuptools$ sudo easy_install pip

We can also directly install PIP:

$ sudo apt-get install python-pip

This allows us to install virtualenv through PIP and build a virtual environment for the Flask project.

install virtualenv
Nginx
$ sudo apt-get install nginx

How to start Nginx:

$ sudo /etc/init.d/nginx start

This time in the browser address bar to enter the server's IP address, see the following page indicates that Nginx has been started:

Installing UWSGI

Before installing UWSGI, we need to solve the uwsgi dependency problem, because Uwsgi is a C language application, so we need the C compiler, as well as Python development related components:

install build-essential python-dev$ sudo pip install uwsgi

Here we have the UWSGI installed,

Open Dry

First, we upload the application to the server, and I'm using git to manage the project, so I just need a git clone to do it:

http://url/of/you/git/repo

If you need to upload the project file from the local, you can use the SCP command, here is not verbose usage. Anyway, we put the project file on the server and then we can use virtualenv to manage the Python environment:

$ virtualenv ENV$ source ENV/bin/activate         # 激活虚拟环境$ pip install -r requirement.txt  # 解决依赖问题$ deactivate                             # 退出依赖环境

Here is the example of Flask 7 lines of code, I created a new folder, called Helloflask, will be the following:

from flask import Flaskapp = Flask(__name__)@app.route("/")def hello(): return "Hello World!"if __name__ == "__main__": app.run(host=‘0.0.0.0‘, port=5001)

Save as hello.py, run try, enter the server public IP address in the browser, add port number 5001 can see the result.

OK, now we use Nginx to assume WEB services.

Delete the default configuration file for Nginx:

/etc/nginx/sites-enabled/default

If you have a heart, you can actually learn some configuration parameters from the Nginx default configuration, but the most reliable way is to look at Nginx's documentation. Here is just a simple attempt at Nginx, here is a simple configuration:

server {    listen 80;    server_name your.website.url    charset utf-8; client_max_body_size 75M; location / { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/home/frank/Documents/helloflask/helloflask_uwsgi.sock; }}

We can save the above content as helloflask_nginx.conf, a little explanation: server_name can be a domain name, you can also write an IP address, Uwsgi_pass is to show Nginx and Uwsgi the way of communication, I use the sock file here, of course You can also use the specified port number in the form of specific can be seen here. Link the Nginx configuration file with a soft link to the Nginx Configuration folder:

/home/frank/Documents/helloflask/helloflask_nginx.conf /etc/nginx/conf.d/

Restart Nginx:

sudo /etc/init.d/nginx restart

At this time to refresh the server before the public IP (or bound domain name), then see is not "welcome to nginx", but "502 bad way", because we have not started Uwsgi, now we will save the following content as Helloflask_ Uwsgi.ini (in XML format is also possible, depending on the document):

  #application ' s base folderbase =/ Home/frank/documents/helloflask #python module to Importapp = Hellomodule =% (APP) home =% (base)/env Pythonpath =% (base)  #socket file ' s locationsocket =/home/frank/ Documents/helloflask/%n.sock #permissions for the socket file Chmod-socket = 666 #the variable that holds a flask application Inside the module imported at line #6 callable = App #location of log fi Leslogto =/home/frank/documents/helloflask/%n.log      

To explain a little bit, the socket specifies the port file that communicates with Nginx. Other parameters, such as the number of threads, number of processors, etc., can be configured after the document is viewed. The above content can be specified by the parameters of the Uwsgi command, typing a line command on the command line can be, in order to "sustainable development", of course, it is better to save the file.

With the Uwsgi command, the--ini parameter:

--ini helloflask_uwsgi.ini &

Specify the configuration file, run Uwsgi in the background, and then refresh the previously opened page to see that the app is working properly.

I tried to run multiple applications on a single server, in fact, only need to change the file name, respectively, processing Uwsgi and Nginx configuration file (Nginx configuration, can be written in the same file, write two server on the line)

Common Command Nginx common commands

Start command:

$ sudo nginx

Or

$ sudo /usr/sbin/nginx

Stop Nginx

stop

Smooth start Nginx

-s reload

The so-called smooth start is to restart Nginx without stopping Nginx, reload the configuration file, and replace the old work process with the new worker process.

Summarize

Once played PHP, compared to the almost one-click deployment of PHP, Python deployment is really cumbersome, but Python's strength lies in the language is simple and elegant, after all, life is short, there will be lost, but I believe this cumbersome is temporary.

Finally give a simple example, in fact, is not enough specification, such as application files should be placed under/var/www/, log files should be placed in the system's log folder and so on, this is just a simple example, more configuration content, we should through UWSGI, Nginx document learning.

Flask+uwsgi+nginx+ubuntu Deployment Tutorials

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.