| | | | |

Hosting a Flask Application on AWS EC2 with NGINX and Gunicorn


This article will take you through the process of hosting a Python Flask application on an AWS EC2 instance (using an Ubuntu server).
We will be using Gunicorn and NGINX as the web app and WSGI.

Creating the AWS EC2 instance

Create an EC2 instance using an Ubuntu server.

Create a security group containing the following rules.

SSH into your EC2 instance using Terminal, Command Line or Powershell.

Getting things ready..

sudo apt-get update
sudo apt install python3-pip
pip3 install flask

Install the web server (Nginx):

sudo apt-get install nginx

Install the Python WSGI server:

sudo apt-get install gunicorn

Setting up the Flask Application on the server

Create the application folder:

mkdir flaskapp

Move your Flask application files into the flaskapp folder.

Configuring the app in the Web Server (Nginx):

Create the configuration file in the NGINX sites-enabled folder:

cd /etc/nginx/sites-enables/
sudo vim flaskapp

Paste the following in the flaskapp file:
The “server_name” should be the Public IP address of your AWS EC2 instance.

    listen 80;
    location / {

Restart the web server for the changes to take affect.

sudo service nginx restart

Start the WSGI server:
The addition of –reload will allow the service to automatically restart when changes are detected.

cd flaskapp
gunicorn -w 4 --reload app:app

Running Gunicorn as a service

cd /etc/systemd/system/

Create a file called gunicorn3.service and paste the following content into the file:

Description=Gunicorn service

ExecStart=/usr/bin/gunicorn3 --workers 3 --bind unix:flaskapp.sock -m 007 app:app

Run the following commands:

sudo systemctl daemon-reload
sudo service gunicorn3 start
sudo service gunicorn3 status

You should not receive any error messages at this point.

TIP. To find the location of the gunicorn3 file, enter the following command:

which gunicorn3

Now that the SOCKET has been created in our flaskapp folder, we need to update the NGINX config file will the absolute directory.

cd /etc/nginx/sites-enabled
sudo vim flaskapp

Replace the proxy_pass attribute with:

proxy_pass http://unix:/home/ubuntu/flaskapp/flaskapp.sock;

Restart the services

sudo service nginx restart
sudo service gunicorn3 restart

Similar Posts

Leave a Reply

Your email address will not be published.