Suppose you have Ubuntu in which you need to deploy Nginx with a Flask application. You need to use a WSGI server, such as Gunicorn. Gunicorn (Green Unicorn) - WSGI HTTP server in Python for UNIX systems. I present a free translation of the article Onur Güzel
How to Run Flask Applications with Nginx Using Gunicorn , where the process of deployment is shown step by step.
Step 0: Requirements
We will use virtualenv to work with a virtual Python environment and pip to work with Python packages. Install them by entering the following command in the terminal:
sudo apt-get install python-virtualenv python-pip
Create a virtual environment and activate it:
virtualenv hello source hello/bin/activate
We note that our prompt now begins with the name of the virtual environment.
Step 1: Application
Install Flask:
')
pip install Flask
After installing Flask using pip, you can write the following code in
hello.py and run it:
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello world!" if __name__ == '__main__': app.run()
Flask has a built-in web server that allows you to run applications. However, it is not scalable and is not suitable for production. On the other hand, there is Gunicorn, which is ready to use for production and provides scalability.
Step 2: Gunicorn
Install Gunicorn:
pip install gunicorn
In order for our Flask application to work with Gunicorn, you need to add 2 and 9 lines from the code to
hello.py :
from flask import Flask from werkzeug.contrib.fixers import ProxyFix app = Flask(__name__) @app.route('/') def hello(): return "Hello world!" app.wsgi_app = ProxyFix(app.wsgi_app) if __name__ == '__main__': app.run()
Now we can run the application with Gunicorn:
gunicorn hello:app
Where
hello is the name of the python file (without the extension). And the
app is the name of the Flask object.
Step 3: Nginx
Create a new server configuration and save the file to:
/etc/nginx/sites-available/hello.confHello.conf content:
server { listen 80; server_name hello.itu24.com; root /path/to/hello; access_log /path/to/hello/logs/access.log; error_log /path/to/hello/logs/error.log; location / { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8000; break; } } }
Create a symbolic link for the sites-enabled directory:
sudo ln -s /etc/nginx/sites-available/hello.conf /etc/nginx/sites-enabled/
Check the configuration for errors:
nginx -t
If everything is fine with the configuration, you can restart Nginx and get a deployed application.