How to Host a Flask API on an AWS EC2 Linux Machine

Hosting a Flask API on an AWS EC2 instance is a straightforward process, but it does require some technical steps. In this blog, we will walk through the steps to set up a Flask API on an Amazon EC2 instance running a Linux operating system. By following this guide, you’ll be able to get your Flask application up and running in no time.

Step 1: Become the Root User

First, you’ll need to switch to the root user to have the necessary permissions for the installation and configuration tasks. Execute the following command:

sudo su -

Step 2: Update Your System

It’s always a good practice to update your system to ensure you have the latest packages and security updates.

yum update -y

Step 3: Create a Directory for Your Project

Create a temporary directory where you will store your project files.

mkdir temp
cd temp/

Step 4: Download Your Project Files from GitHub

Ensure your required project files are in a GitHub public repository. Download the files using wget.

wget https://github.com/ranjithkumarmadhavan/test/archive/refs/heads/main.zip

Step 5: View the List of Files in the Directory

List the files in your current directory to confirm the download.

ls -lrt

Step 6: Unzip the Downloaded File

Unzip the downloaded repository to access your project files.

unzip main.zip

Step 7: Navigate to Your Project Directory

Change directory to the unzipped project folder.

cd test-main

Step 8: Set Up a Python Virtual Environment

Create a virtual environment to manage your project dependencies.

python3 -m venv venv

Step 9: Activate the Virtual Environment

Activate the virtual environment to use the installed packages.

source venv/bin/activate

Step 10: Install the Required Packages

Install the necessary packages listed in your requirements.txt file.

pip install -r requirements.txt

Step 11: Run Your Flask Application

Run your Flask application to ensure everything is set up correctly.

python main.py

Step 12: Enable Port 5000 in Your Security Group

In the AWS Management Console, navigate to your EC2 instance’s security group settings and add a rule to allow inbound traffic on port 5000. This step is crucial as it will allow external access to your Flask API.

Step 13: Use Gunicorn to Serve Your Flask Application

Gunicorn is a Python WSGI HTTP Server for UNIX. Use it to serve your Flask application on port 5000.

gunicorn --bind 0.0.0.0:5000 main:app

Step 14: Run Gunicorn in the Background

To keep your application running in the background, append the & symbol to the command.

gunicorn --bind 0.0.0.0:5000 main:app &

By following these steps, you will have your Flask API hosted on an AWS EC2 Linux machine, accessible over the internet. This setup is robust for development and testing purposes. For a production environment, consider additional configurations such as setting up a reverse proxy with Nginx and securing your application with SSL/TLS.

Leave a Comment