Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Server \ Ubuntu deployment Flask + UWSGI + Nginx Comments     - Linux System Getting Started Tutorial: mounted directly in Linux LVM partition (Linux)

- Ubuntu How to install screen recording tool Simple Screen Recorder 0.3.1 (Linux)

- How to configure Apache Solr on Ubuntu 14/15 (Server)

- Use HugePages optimize memory performance (Database)

- The Gitlab migrated to Docker container (Server)

- Rails project prepared some tips small experience (Linux)

- C # how to generate a folder or file automatically rename (Programming)

- JITwatch installation under Linux (Linux)

- Apache POI Excel Document Processing (Linux)

- Configuring LIDS build Linux kernel security intrusion detection system (Linux)

- grub boot error resolution examples (Linux)

- to install the deployment of LVS under CentOS 7.0 (Server)

- Installation and Configuration Munin monitoring server on Linux (Server)

- CentOS yum install LAMP (Server)

- CentOS minimal network is unavailable resolved (Linux)

- Sorting Algorithm (1) Quick Sort C ++ implementation (Programming)

- The AWK use Cygwin tools mysql binlog log viewer (Database)

- Source compiler install Nginx (Server)

- Linux Operating System Security Study (Linux)

- Orionode source Linux Mint installation (Linux)

  Ubuntu deployment Flask + UWSGI + Nginx Comments
  Add Date : 2018-11-21      
  Ali to start with a cloud server is Ubuntu 14.04 32-bit version, the initial consideration is to taste fresh just bought a minimum with the price and the price in foreign countries to buy space counted fairly, right (probably a year to your 100 more), but it feels very good, the speed that is one word: fast.

Since the defection to Linux world, for all large and have a kind of software development framework and not really very pleasant feeling, personally prefer to use those small but excellent software development framework and high-performance power generation, So I now the first language is Python and Coffee, of course, is the development framework AngularJS (front-end) + Flask (rear end), within the scope of this article on AngularJS and Flask narrative scope of this article to resolve the Flask last kilometer problem: Linux deployment .

Deployment programs I use are:

Web server uses uwsgi host Flask
Supervisor with reference uwsgi for routine service start
Based on Nginx as a reverse proxy
First, Ali cloud server via SSH command in the machine terminal for remote connections

ssh root @ cloud server address
After entering your password to access all operations with a local terminal to complete.

Installing Python environment

Next is the python, the default environment Ubuntu has python 2.7 preinstalled so only need to install the python pip installation tool can be. pip to install some python based application software tools will be used frequently in the following.


But does not know if python [pip | http: //pypi.python.org/] it is best to hurry the brain make it, instructions are as follows:

sudo apt-get install pip

Different projects may reference various dependencies, in order to avoid conflicts between applications and versions and caused "dependency hell"
[Virtualenv | https://virtualenv.readthedocs.org/en/latest/] is that we must product the python project. VirtualEnv Python applications can be created for each separate development environment, so that they affect each other, Virtualenv able to do:

Install the new kit in the case without permission
Different applications can use different versions of packages
Suite upgrade does not affect other applications

sudo pip install virtualenv
After installation VirtualEnv just run virtualenv directory name in the project directory you can create a virtual environment folder, and then enable the activate command to enable the python virtual environment, as follows:

I assume that the project directory called / home / www / my_flask, first install the virtual environment (virtual environment I used to use a directory called venv)

my_flask root $ virtualenv venv

>> New python executable in venv / bin / python
>> Installing setuptools, pip ... done.
Under the project will create a new directory venv catalog, which is to run the command python basic tools and environments, and packages. Then enable the environment, using the current state of the command line to enter the virtual environment into the virtual environment, all operations will be installed python packages and references contained within the virtual environment, without affecting the overall python environment.

my_flask root $ source venv / bin / activate

(Venv) my_flask root $
After calling the activate command before the command symbol will appear (venv) words. Exit the virtual environment through deactivate.

Installation uWSGI

The actual production run Environmental Choice Flask is not much more mature is [Gunicorn | http: //gunicorn.org/] and [uWSGI | https: //github.com/unbit/uwsgi], the configuration is heard Gunicorn simple, but unfortunately I have not configured success, I now use the uWSGI. Then install uWSGI it.

(Venv) my_flask root $ pip install uwsgi
Do not use sudo in a virtual environment, because there is no authority virtualenv requirements.

The installation is very quick, a basic seconds. After installation is complete, we can not be put down uWSGI table in the back came configured his return, because we first want to key Flask environment and our internal project files to the server directory.

Installation Flask

I am a one-time installation Flask and his dependence associated with the list of documents, which will be faster. I have a list of references is this:

Flask == 0.10.1
Flask-Login == 0.2.11
Flask-Mail == 0.9.1
Flask-Moment == 0.4.0
Flask-PageDown == 0.1.5
Flask-SQLAlchemy == 2.0
Flask-Script == 2.0.5
Flask-WTF == 0.10.2
Flask-Cache == 0.13.1
Flask-Restless == 0.15.0
Flask-Uploads == 0.1.3
Jinja2 == 2.7.3
Mako == 1.0.0
Markdown == 2.5.1
MarkupSafe == 0.23
SQLAlchemy == 0.9.8
WTForms == 2.0.1
Werkzeug == 0.9.6
html5lib == 1.0b3
itsdangerous == 0.24
six == 1.8.0
awesome-slugify == 1.6
You can imagine that if a installed a non-crazy is not available.
Install manifest file:

(Venv) my_flask root $ pip install -r requirements.txt
In this still heavily mention: Be sure to pay attention to before running the installer enabled the python virtual environment, otherwise it will go directly into the global!

Project files

The next step is to upload Flask project file, before I in the major of "reproduced specialist" where to find a lot of information, but most of the above plus a standard Flask run file In this step, although it can be a model, but to tell the truth this is very confusing, and why? First look at the code it:

from flask import Flask
app = Flask (__ name__)
@ App.route ( "/")
def hello ():
    return "Hello World!"
Within the production environment, who would use such code it, this is only the most simple introductory Fan Flask, Flask my app project is done within the package, I believe many people are doing in the outside of the package we use Flask Script writing manage.py file as a startup file, which is more convenient to support a variety of projects, including the ability to install under the FastCGI window.

So I have this manage.py look like this:

#! / Usr / bin / env python
import os

if os.path.exists ( 'env.'):
    print ( 'Importing environment from .env ...')
    for line in open ( 'env.'):
        var = line.strip (). split ( '=')
        if len (var) == 2:
            os.environ [var [0]] = var [1]

from app import create_app
from flask.ext.script import Manager, Shell

# Create app by configuring
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." ""

if __name__ == '__main__':
    manager.run ()
I do so to the development environment can be run Flask:

python manage.py runserver
More detailed practices, please refer [Flask Script | http: //flask-script.readthedocs.org/en/latest/] Extended

Well, we can use an SSH FTP tool Flask project files uploaded to the server, the following is the entire project file structure:

www /
 venv // virtual directory
 python2.7 -> /usr/include/python2.7
bin -> / home / shenye / shenyefuli / bin
 include -> / home / shenye / shenyefuli / include
 lib -> / home / shenye / shenyefuli / lib
 app // Flask program directory
 __init__.py // This is the package file. Skip this directory there are other files here

Configuration uwsgi

Well, the preparatory work of the project has been done, it is time to go back and configure uwsgi, and its specific directives can see it's official documents, we are here to adopt one of these commands way: configure start. I use .ini files as configured, create a confg.ini under the project directory (specifically see below) can be written to perform such

(Venv) my_flask root $ uwsgi config.ini
I think that is the easiest way, but also easy to change. Well, the important part here, config.ini is written like this:


# Uwsgi address and port used by the boot
socket =

# Point to Site Directory
chdir = / home / www /

# Python launcher file
wsgi-file = manage.py

# Python program within the variable name used to start the application
callable = app

# Processors
processes = 4

# Threads
threads = 2

# Status detection address
stats =
Note: callable = app this app is a variable manage.py file within the type of the variable is Flask of application class.

Run uwsgi

`` `
(Venv) my_flask root $ uwsgi config.ini

[UWSGI] getting INI configuration from config.ini

*** Starting uWSGI 2.0.8 (64bit) on [Fri Dec 19 14:34:11 2014]
// Omitted here those useless startup information
Stats server enabled on fd: 15 ***
`` `

OK, now has normal start uwsgi and Flask project into which a, ctrl + c to close the program. But this is only the command to start the form, you want to make along with the server is up and running as a background service is the actual operating environment required. So then we need to install another tool to guide uwsgi.

Installation Supervisor

[Supervisor | http: //supervisord.org/configuration.html] can launch multiple applications, the most important thing is, when an application Crash, he can automatically restart the application to ensure availability.

sudo apt-get install supervisor
The global configuration file location in Supervisor:

Under normal circumstances we do not need to make any changes to it, you only need to add a new file in the * .conf

Under it, then we will establish a new supervisor uwsgi of a configuration used to start my_flask project (named: my_flask_supervisor.conf):

[Program: my_flask]
# Start a command entry
command = / home / www / my_flask / venv / bin / uwsgi /home/www/my_flask/config.ini

# Command program directory
directory = / home / www / my_flask
# Username to run the command
user = root

autostart = true
autorestart = true
# Log Address
stdout_logfile = / home / www / my_flask / logs / uwsgi_supervisor.log
Start Service

sudo service supervisor start
Termination of service

sudo service supervisor stop
Install Nginx

[Nginx | http: //nginx.com/] is a lightweight, high performance, small footprint, can be a good deal with high concurrent reverse proxy software.

sudo apt-get install nginx
Configure Nginx

Configure Nginx on Ubuntu is very simple, do not go just to change the default nginx.conf

/ Ext / nginx / sites-available / default
File replace it.

Create a new default document:

server {
listen 80;
server_name XXX.XXX.XXX; # public address

location / {
include uwsgi_params;
uwsgi_pass; # point to the internal address uwsgi applied, all requests will be forwarded to the processing uwsgi
uwsgi_param UWSGI_PYHOME / home / www / my_flask / venv; # point to the virtual environment directory
uwsgi_param UWSGI_CHDIR / home / www / my_flask; # to the site root directory
uwsgi_param UWSGI_SCRIPT manage: app; # specify the startup program
The default configuration file is replaced and you're done!
Also, change the configuration also need to remember to restart it nginx:

sudo service nginx restart
to sum up

Ali cloud servers running speed is very good, with Flask + uWSGI + nginx this high-performance architecture, the entire site is extremely fast response speed, response time per page is less than 0.1s, compared to before I use C # deployment Avarix on the website (the same program, different language) per response rate of at least 2s this is simply 200: 1 performance, of course, I did not go to the busy professionals who use software to measure the difference between the two, write the purpose of this article is to make a record for later review.
- Lua study notes under ubuntu (Linux)
- Add local search to your Android app (Programming)
- Zypper command for SUSE Linux package management (Linux)
- Java factory pattern (Factory mode) (Programming)
- Oracle Linux 7.1 install Oracle 12C RAC (Database)
- Django Signals from practice to source code analysis (Programming)
- Connect to the Oracle Database Help class (Database)
- Linux NFS service fixed ports and firewall configuration (Linux)
- Hyper-V virtual hard disk how to copy files to and attached to the virtual machine (Linux)
- SecureCRT 7.0 Log Ubuntu 12.04 server via SSH service under Vmware (Server)
- Ubuntu under shadowsocks configuration instructions (Linux)
- Dialogue UNIX:! $ # @ *% (Linux)
- MySQL configuration file my.cnf increase the log file parameter error (Database)
- RVM installation instructions (Linux)
- AWR Report (Database)
- Linux simple commands (Linux)
- ORA-28000 the account is locked fault simulation (Database)
- Thrift 0.9.3 compiler installation under Ubuntu (Linux)
- Spring inject a type of object to enumerate (Programming)
- Snapshot DataGuard (Database)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.