Deployment of Flask App|Gunicorn| Nginx|AWS-EC2

Chachrayatin
2 min readAug 7, 2020

The blog will cover the whole process of deployment of a flask app on AWS-EC2 using Gunicorn & Nginx in just 7 Steps

Architecture

Steps to deploy the Flask App on EC2:

1. Install Ngnix

sudo apt-get update
sudo apt install nginx

2. Install Python, Pip and Required python packages

sudo apt install python3
sudo apt install python3-pip
pip3 install virtualenv
pip3 install Flask
pip3 install Flask-RESTful
pip3 install gunicorn

3. Create and activate Virtual Environment

python3 -m venv base
source base/bin/activate

4. Create a Guincorn Service

cd /etc/systemd/system
vim gunicorn.service

Paste the following code:

[Unit]
Description=Gunicorn Service
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/my-flask-app
ExecStart=/home/ubuntu/base/bin/gunicorn — workers 3 — error-logfile /home/ubuntu/gunicorn_logs/error_log — bind unix:my_flask_app.sock -m 007 app:app

Note:
a. Replace the WorkingDirectory path with your path
b. Use command “pwd” at your project to the exact path of the project
c. Use command “which gunicorn” after activating your venv to know the path of the guinicorn used
d. Create a “gunicorn_logs” directory for error logs of gunicorn

5. Configure Nginx

cd /etc/nginx/sites-available
vim default

Paste the following code:
server{
listen 80;
server_name PrivateIP_of_your _EC2 instance;

location / {
proxy_pass http://unix:/home/ubuntu/my-flask-app/my_flask_app.sock;
}
}

Note:
Add Private IP of your EC2 instance here.

6. Check Nginx Config for any error:

use: nginx -t
Output should be:
Configuration test OK

7. Reload Gunicorn Service and Nginx

sudo systemctl daemon-reload
sudo service gunicorn stop
sudo service gunicorn start
sudo service gunicorn status #output should be running here
sudo service nginx stop
sudo service nginx start
sudo service nginx status #output should be running here

Hurray !! You just deployed your Flask App
Visit http://your_ec2_private_ip
Your app should be up and running.

If still can’t access your project:
Check:
1. vim /var/log/nginx/access.log
2. vim /var/log/nginx/error.log
3. vim /home/ubuntu/gunicorn_logs/error_log

--

--