Deploying flask application on the EC2 instance

Anurag
AWS Tip
Published in
4 min readNov 4, 2022

--

Follow the below steps:

Step-1
Step-2
Step-3

SSH into EC2 instance — Deploy Flask application on EC2

ssh -i flask.pem ubuntu@[ip_address]

If permission is denied, run the following command:

chmod 400 flask.pem

Configure EC2 instance for flask — Deploy Flask application on EC2

  1. Update your system:

2. Check if python is installed.

3. Check for package manager:

4. Then install your required libraries.

5. Install web server:

sudo apt-get install nginx
sudo apt-get install gunicorn3

6. Gunicorn3 → Python web server gateway interface. Works with several web frameworks. It will create a unique socket, and it will serve the response to the nginx request via the web server gateway interface protocol.

7. Nginx will face the outside world/ internet. It will directly serve the media file (static files like images, and CSS). Nginx cannot directly talk to the flask application. We need something in between the web server, i.e., Nginx, and our flask application.

Create flask app & configure Nginx — Deploy Flask application on EC2

2. Step -2

3. This is a very basic configuration of the web server that is defined for this tutorial. Save the above file.

4. Restart the Nginx:

sudo service nginx restart

5. Please read the document of gunicorn3 as we can also pass another parameter like a thread.

To start the service:

gunicorn3 app:app

Deploy Flask app & security groups — Deploy Flask application on EC2

1. Let’s open the port so that we can run our app publicly. To deal with the port, we need to configure security groups.

2. Here you will find the security group.

3. Open port number 80

4. Re-run gunicorn and now your app must be working.

Create Gunicorn as a Service — Deploy Flask application on EC2

When you don’t need that gunicorn running then see this tutorial: YouTube

  1. To create a service file:

2. Here we are going to create the dot service file.

3. Now, here we will define two sections, unit and service.

4. To know the path: which gunicorn3

5. We need to reload the daemon:

sudo systemctl daemon-reload

6. Once this is done, we also need to update the Nginx file with a socket path instead of a local host path (or local host IP address).

If you have any questions or suggestions regarding the blog, please comment down below. In case you have not followed me yet, please do. I hope to see you again for another blog.

Till then, take care!

--

--

Currently working as Product Manager who is also a passionate engineer with an experience in Artificial Intelligence.