Deploying FastAPI with Docker
A Complete Guide to Containerizing and Deploying a FastAPI Application
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Docker is a powerful platform for developing, shipping, and running applications in isolated environments called containers. In this article, we’ll explore how to containerize a FastAPI application using Docker and deploy it.
1. Setting Up Your Environment
Before we begin, ensure you have Docker installed on your system. You can download and install Docker from Docker’s official website.
2. Creating a Simple FastAPI Application
First, let’s create a simple FastAPI application. Create a new directory for your project and set up the following structure:
fastapi_docker/
├── app/
│ ├── __init__.py
│ ├── main.py
├── Dockerfile
├── requirements.txt
└── README.md
Example: 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}
Example: requirements.txt
fastapi
uvicorn
3. Creating a Dockerfile
A Dockerfile is a script that contains a series of instructions on how to build a Docker image. Create a Dockerfile
in the root directory of your project.
Example: Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.9
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
4. Building the Docker Image
With your Dockerfile in place, you can now build your Docker image. Navigate to the root directory of your project and run the following command:
docker build -t fastapi-docker .
This command builds an image named fastapi-docker
from the Dockerfile in the current directory.
5. Running the Docker Container
After building the Docker image, you can run it as a container. Use the following command to start a container from the image you built:
docker run -d -p 80:80 fastapi-docker
This command runs the container in detached mode (-d
) and maps port 80 of the container to port 80 on your host machine (-p 80:80
).
6. Accessing Your FastAPI Application
With the container running, you can access your FastAPI application by navigating to http://localhost
in your web browser. You should see the JSON response {"Hello": "World"}
.
You can also access the interactive API documentation provided by FastAPI at http://localhost/docs
.
7. Docker Compose for Multi-Container Applications
If your FastAPI application requires additional services like a database, you can use Docker Compose to manage multiple containers. Create a docker-compose.yml
file in the root directory of your project.
Example: docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "80:80"
db:
image: postgres
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: fastapi_db
Run the following command to start all the services defined in the docker-compose.yml
file:
docker-compose up -d
8. Deploying to a Cloud Service
To deploy your FastAPI application to a cloud service, you can push your Docker image to a container registry like Docker Hub or AWS ECR, then pull and run the image on a cloud server.
Example: Pushing to Docker Hub
- Tag your Docker image:
docker tag fastapi-docker YOUR_DOCKERHUB_USERNAME/fastapi-docker
2. Push the image to Docker Hub:
docker push YOUR_DOCKERHUB_USERNAME/fastapi-docker
3. On your cloud server, pull the image and run it:
docker pull YOUR_DOCKERHUB_USERNAME/fastapi-docker
docker run -d -p 80:80 YOUR_DOCKERHUB_USERNAME/fastapi-docker
Conclusion
Dockerizing your FastAPI application allows you to create portable, consistent environments that can run anywhere Docker is supported. This guide has walked you through the process of containerizing a FastAPI application and deploying it using Docker. With Docker, you can simplify the deployment process, ensuring that your application runs smoothly in different environments.