How to Deploy a FastAPI Application on AWS with Docker
Deploying applications efficiently is crucial for modern web development, and FastAPI, with its high performance and ease of use, has emerged as a popular choice for building APIs. When combined with Docker, deploying FastAPI applications becomes even more seamless. In this guide, we will walk through the process of deploying a FastAPI application on AWS using Docker, providing you with actionable insights, code examples, and troubleshooting tips along the way.
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 built on top of Starlette for the web parts and Pydantic for the data parts. FastAPI is designed to be easy to use, with automatic interactive documentation and support for asynchronous programming.
Use Cases for FastAPI:
- Building RESTful APIs quickly
- Developing microservices
- Creating data-driven applications
- Machine learning model serving
Why Use Docker?
Docker is a platform that allows you to automate the deployment of applications inside lightweight, portable containers. Using Docker provides several benefits:
- Consistency: Develop, test, and run your applications in the same environment.
- Isolation: Each application runs in its own container, avoiding conflicts.
- Scalability: Easily scale your application by managing containers.
Prerequisites
Before you begin, ensure you have the following:
- An AWS account
- Docker installed on your local machine
- Basic knowledge of Python and FastAPI
- AWS CLI configured with your credentials
Step 1: Create a FastAPI Application
Let’s start by creating a simple FastAPI application. Create a directory for your project and navigate into it:
mkdir fastapi-aws-docker
cd fastapi-aws-docker
Now, create a file named 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, create a Dockerfile
in the same directory to define the container environment:
# Use the official Python image from Docker Hub
FROM python:3.9-slim
# 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 FastAPI application code
COPY . .
# Command to run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Step 3: Create a Requirements File
Create a requirements.txt
file to specify the dependencies:
fastapi
uvicorn
Step 4: Build the Docker Image
Now, build the Docker image by running the following command in your terminal:
docker build -t fastapi-aws-app .
Step 5: Run the Docker Container Locally
Before deploying to AWS, let’s test the application locally:
docker run -d -p 8000:80 fastapi-aws-app
You can now access your FastAPI application at http://localhost:8000
. Navigate to http://localhost:8000/docs
to see the interactive API documentation.
Step 6: Push the Docker Image to AWS ECR
- Create a Repository in ECR:
-
Go to the AWS Management Console, navigate to ECR (Elastic Container Registry), and create a new repository.
-
Authenticate Docker to Your ECR:
Run this command to authenticate:
bash
aws ecr get-login-password --region your-region | docker login --username AWS --password-stdin your-account-id.dkr.ecr.your-region.amazonaws.com
- Tag and Push Your Docker Image:
Tag your image with the ECR repository URI:
bash
docker tag fastapi-aws-app:latest your-account-id.dkr.ecr.your-region.amazonaws.com/fastapi-aws-app:latest
Push the image:
bash
docker push your-account-id.dkr.ecr.your-region.amazonaws.com/fastapi-aws-app:latest
Step 7: Deploy on AWS Elastic Beanstalk
- Create a New Elastic Beanstalk Application:
-
Go to the Elastic Beanstalk console and create a new application.
-
Create a New Environment:
-
Select "Web server environment" and choose "Docker" as the platform.
-
Configure the Environment:
-
Under "Application code," select your ECR image.
-
Launch the Environment:
- Review the settings and launch the environment. This may take a few minutes.
Step 8: Access Your Application
Once your environment is up, you will receive a URL to access your FastAPI application. Navigate to that URL, and you should see your API is live!
Troubleshooting Tips
- Container Not Starting: Check the logs in the Elastic Beanstalk console for errors.
- Image Not Found: Ensure that the image was pushed to the correct ECR repository.
- Networking Issues: Verify that your security groups and IAM roles are correctly configured.
Conclusion
Deploying a FastAPI application on AWS with Docker is a straightforward process that allows you to leverage the power of containerization and the scalability of AWS. By following these steps, you can ensure that your FastAPI application is not only easy to deploy but also reliable and efficient. With the knowledge gained from this guide, you can now explore further optimizations and scaling strategies for your applications. Happy coding!