2-how-to-deploy-a-fastapi-application-on-aws-using-docker.html

How to Deploy a FastAPI Application on AWS Using Docker

Deploying a FastAPI application on AWS using Docker can seem daunting at first, but with the right guidance, it can become a straightforward process. FastAPI is an increasingly popular web framework for building APIs with Python, known for its high performance and ease of use. Docker streamlines application deployment by providing consistent environments. In this article, we’ll walk through the complete process of deploying a FastAPI application to AWS using Docker, including code examples and actionable insights.

What is FastAPI?

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use and offers several features that enhance productivity:

  • Automatic API documentation: FastAPI generates interactive API documentation using Swagger UI and ReDoc.
  • Data validation: Built-in data validation with Pydantic ensures the correctness of incoming requests.
  • Asynchronous support: FastAPI fully supports asynchronous programming, making it suitable for handling high loads.

Why Use Docker?

Docker is a platform that enables developers to automate the deployment of applications inside lightweight, portable containers. Using Docker for your FastAPI application offers several benefits:

  • Consistency across environments: Docker ensures that your application runs the same way in development, testing, and production.
  • Isolation: Each application runs in its own container, avoiding conflicts with other applications.
  • Scalability: Docker containers can be easily scaled horizontally to handle increased loads.

Prerequisites

Before we start, ensure you have the following:

  • An AWS account
  • Docker installed on your local machine
  • Basic knowledge of Python and FastAPI
  • AWS CLI installed and configured

Step-by-Step Guide to Deploy FastAPI on AWS Using Docker

Step 1: Create a FastAPI Application

Let’s start by creating a simple FastAPI application. Create a new directory for your project and a main Python file, main.py.

mkdir fastapi-aws-docker
cd fastapi-aws-docker
touch main.py

Add the following code to main.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Step 2: Create a Dockerfile

Next, we need to create a Dockerfile to define our application’s environment.

Create a file named Dockerfile in the same directory:

touch Dockerfile

Add the following content to the Dockerfile:

# Use the official Python image from the Docker Hub
FROM python:3.9

# Set the working directory
WORKDIR /app

# Copy the requirements file and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY . .

# Expose the port the app runs on
EXPOSE 8000

# Command to run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Step 3: Create a Requirements File

To run our FastAPI application, we need to install the necessary dependencies. Create a requirements.txt file:

touch requirements.txt

Add the following content to the requirements.txt file:

fastapi
uvicorn

Step 4: Build the Docker Image

Now, it’s time to build the Docker image. Run the following command in your terminal:

docker build -t fastapi-aws-docker .

Step 5: Test Your Application Locally

You can test your application locally before deploying it to AWS. Run the following command to start the Docker container:

docker run -d -p 8000:8000 fastapi-aws-docker

Open your browser and navigate to http://localhost:8000. You should see the message {"Hello": "World"}. You can also visit http://localhost:8000/items/1?q=test to see the item endpoint in action.

Step 6: Push the Docker Image to AWS ECR

To deploy the application on AWS, we need to push our Docker image to Amazon Elastic Container Registry (ECR).

  1. Create a new ECR repository:

bash aws ecr create-repository --repository-name fastapi-aws-docker

  1. Authenticate Docker to your ECR:

bash aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <your-account-id>.dkr.ecr.us-east-1.amazonaws.com

  1. Tag the Docker image:

bash docker tag fastapi-aws-docker:latest <your-account-id>.dkr.ecr.us-east-1.amazonaws.com/fastapi-aws-docker:latest

  1. Push the Docker image to ECR:

bash docker push <your-account-id>.dkr.ecr.us-east-1.amazonaws.com/fastapi-aws-docker:latest

Step 7: Deploy on AWS Elastic Beanstalk

  1. Create a new Elastic Beanstalk application:

Navigate to the AWS Elastic Beanstalk console and create a new application. Choose "Docker" as the platform.

  1. Configure your environment:

Set the environment type to "Load balanced" for better performance and scalability.

  1. Deploy your application:

Upload the Docker image from ECR during the environment creation process. AWS Elastic Beanstalk will handle the rest, allowing you to focus on your application.

Conclusion

Congratulations! You have successfully deployed a FastAPI application on AWS using Docker. This method not only helps maintain consistency across environments but also leverages the power of AWS for scalability and reliability.

As you continue to develop your application, consider exploring additional features of FastAPI and AWS services, such as API Gateway for managing your API endpoints or RDS for database integration. With FastAPI and Docker, the possibilities are endless!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.