• Get In Touch
May 30, 2016

Deploy Flask Applications with Gunicorn and Nginx on Ubuntu 14.04

Want your very own server? Get our 1GB memory, Xeon V4, 25GB SSD VPS for £10.00 / month.
Get a Cloud Server

Introduction

Flask was created by Armin Ronacher of Pocoo which is an international group of Python enthusiasts formed in 2004. Flask is a lightweight Python web framework based on Werkzeug and Jinja 2, Flask tackles Routing, HTML template rendering, Sessions etc. If you are building web applications on Linux, then I highly recommend using Flask.

Flask is an extremely functional and powerful framework that is most popular and very much extensible with a great choice of third party libraries.

Flask is called a micro framework because it does not presume or force a developer to use a particular tool or library. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. However, Flask supports extensions that can add application features as if they were implemented in Flask itself.

The Gunicorn also known as “Green Unicorn” is a Python Web Server Gateway Interface (WSGI) HTTP server. It is a pre-fork worker model, ported from Ruby’s Unicorn project.

The Gunicorn server is broadly compatible with a number of web frameworks, simply implemented, light on server resources and fairly fast.

Features

Flask was designed to be easy to use and extend. Flask is great for all kinds of projects. It’s especially good for prototyping. Flask depends on two external libraries: the Jinja2 template engine and the Werkzeug WSGI toolkit.

Despite the lack of a major release, Flask has become extremely popular among Python enthusiasts. Flask provides several very useful features, some of them are listed below.

  1. Flask has a lightweight and modular design, so it easy to transform it to the web framework you need with a few extensions without weighing it down
  2. HTTP request handling functionality and High Flexibility
  3. Support for secure cookies (client side sessions) and Integrated support for unit testing
  4. Built-in development server and fast debugger
  5. Flask documentation are comprehensive, full of examples and well structured. You can even try out some sample application to really get a feel of Flask.
  6. Jinja2 templating and WSGI 1.0 compliant

In this tutorial, we will learn how to set up the Gunicorn application server to launch the application and Nginx to act as a front end reverse proxy.

Requirements

  • A server running Ubuntu-14.04.
  • A static IP Address for your server.
  • A non-root user account with sudo privilege set up on your server.

Install Nginx

Nginx is a free, open-source, high-performance HTTP server and reverse proxy server, also known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.

It has reached its popularity due to being light weight, relatively easy to work with and easy to extend with add-ons and plug-ins.

Before starting, update the system by running the following commands:

sudo apt-get update

sudo apt-get upgrade

Then, install Nginx by running the following command:

sudo apt-get install nginx

Next, start Nginx service by running the following command:

sudo /etc/init.d/nginx start

Then, add Nginx service to start at boot time by running the following command:

sudo update-rc.d nginx defaults

You should see the following output:

     Adding system startup for /etc/init.d/nginx ...
       /etc/rc0.d/K20nginx -> ../init.d/nginx
       /etc/rc1.d/K20nginx -> ../init.d/nginx
       /etc/rc6.d/K20nginx -> ../init.d/nginx
       /etc/rc2.d/S20nginx -> ../init.d/nginx
       /etc/rc3.d/S20nginx -> ../init.d/nginx
       /etc/rc4.d/S20nginx -> ../init.d/nginx
       /etc/rc5.d/S20nginx -> ../init.d/nginx

Install Flask and Gunicorn

Now, you will need to set up a virtual environment that will keep the application and its dependencies isolated from the main system.

You can use pip to install virtualenv and Flask. If pip is not installed, you can install it by running the following command:

sudo apt-get install python-pip python-dev

Now, install Flask and Gunicorn by using the following pip command:

sudo pip install flask gunicorn

Next, you will need to set up a virtual environment in order to isolate your Flask application from the other Python files on the system.

You can install virtualenv with the following command

sudo pip install virtualenv

Now, create a directory structure for your Flask project.

sudo mkdir -p /opt/flaskproject/flaskproject

Move into the directory after you create it:

cd /opt/flaskproject/flaskproject

Next, create a virtual environment to store your Flask project’s Python requirements by running:

virtualenv flaskenv

The output looks something like this:

    New python executable in /opt/flaskproject/flaskproject/flaskenv/bin/python
    Installing setuptools, pip, wheel...done.

The above command will install a local copy of Python and pip into a directory called flaskenv within your project directory.

Before installing applications within the virtual environment, you need to activate it. You can do so by typing:

source flaskenv/bin/activate

The output will look something like this:

    (flaskenv) root@Node1:/opt/flaskproject/flaskproject# 

Set Up a Flask Application

Now you are in your virtual environment, you can proceed to design your application:

Create sample Flask app with name flaskproject.py inside flaskproject directory:

sudo nano /opt/flaskproject/flaskproject.py

Add the following code:

    from flask import Flask
    application = Flask(__name__)

    @application.route("/")
    def hello():
        return "This is sample Flask App"

    if __name__ == "__main__":
        application.run(host='0.0.0.0')

The above code basically defines what content to present when the root domain is accessed. Save and close the file when you’re finished.

You can now test your Flask app by running the following command:

sudo python /opt/flaskproject/flaskproject.py

You should see the following output:

     * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Now, open your favourite web browser and type the URL http://server-ip-address or use the following curl command with port 5000:

curl http://server-ip-address:5000

You should see the following output:

    This is sample Flask App

When you are finished, hit CTRL-C in your terminal to stop the Flask development server.

Next, you will need to create WSGI file that will serve as the entry point for your application. This will tell your Gunicorn server how to interact with the application.

To do so, create file wsgi.py inside flaskproject directory:

sudo nano /opt/flaskproject/wsgi.py

Add the following code:

    from flaskproject import application

    if __name__ == "__main__":
        application.run()

The above code import the Flask instance from your application and then run it.

Save and close the file when you are finished.

Next, you will need to test Gunicorn to serve the project. Before starting, you should check that Gunicorn can correctly.

You can do this by passing it the name of your entry point with the interface and port to bind to so that it will be started on a publicly available interface:

cd /opt/flaskproject

gunicorn --bind 0.0.0.0:8000 wsgi

You should see the following output:

    [2016-05-18 21:40:07 +0000] [1457] [INFO] Starting gunicorn 19.5.0
    [2016-05-18 21:40:07 +0000] [1457] [INFO] Listening at: http://0.0.0.0:8000 (1457)
    [2016-05-18 21:40:07 +0000] [1457] [INFO] Using worker: sync
    [2016-05-18 21:40:07 +0000] [1462] [INFO] Booting worker with pid: 1462

Now, you can test your Gunicorn by running the following curl command:

curl http://server-ip-address:8000

You should see the following output:

    This is sample Flask App

After confirmed that Gunicorn is functioning properly, press CTRL-C in your terminal window.

Also, you can deactivate your virtual environment by running the following command:

deactivate

Create an Upstart Script

Next, you will need to create an Upstart script that will allow Ubuntu’s init system to start Gunicorn server and serve your Flask application during boot time.

To do so, create flaskproject.conf file inside /etc/init directory.

sudo nano /etc/init/flaskproject.conf

Add the following content:

    #Upstart Script

    description "gunicorn"

    respawn
    respawn limit 15 5

    start on runlevel [2345]
    stop on runlevel [06]

    env SCRIPTS_BIN=/opt/flaskproject/flaskproject/flaskenv/bin

    script
    cd $SCRIPTS_BIN
    cd /opt/flaskproject/
    exec gunicorn --workers 3 --bind unix:flaskproject.sock -m 007 wsgi
    end script

Save and close the file when you are finished.

You can now start the process by running the following command:

sudo start flaskproject

Configure Nginx to Proxy Requests

Gunicorn application server should now be up and running and waiting for requests on the socket file in the flaskproject directory.

Now, you will need to configure Nginx to pass web requests to that socket.

To do this, create a new server block configuration file in Nginx’s sites-available directory:

sudo nano /etc/nginx/sites-available/flaskproject

Add the following content:

    # Configuration for Nginx
    server {
        # Configuration for Nginx
        listen 80;
        #Specify domain name or IP Address
        server_name server-ip-address;

        location / {
            include proxy_params;
            proxy_pass http://unix:/opt/flaskproject/flaskproject.sock;
        }
    }

Save and close the file when you’re finished.

Now, enable Nginx server block configuration file, symlink the file to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/flaskproject /etc/nginx/sites-enabled

You can test Nginx configuration by running the following command:

sudo nginx -t

You will see the following output:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful

Now, start Nginx service by running the following command:

sudo /etc/init.d/nginx start

Congrats!.. You should now able to see your application by running the following curl command:

curl http://server-ip-address

You should see the following output:

    This is sample Flask App

Conclusion

In this tutorial, you have learned to create a Flask application within a Python virtual environment, create WSGI entry point, configure the Gunicorn app server to provide this function and created an Nginx server block that passes web client traffic to the application server.
You can also design your own app and serve the flask applications.

Want your very own server? Get our 1GB memory, Xeon V4, 25GB SSD VPS for £10.00 / month.
Get a Cloud Server

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]