FastAPI in Containers - Docker | FastAPI + Docker + Compose
Table of Contents
Introduction
In this tutorial, we will learn how to containerize a FastAPI application using Docker and Docker Compose. This process allows you to package your application and its dependencies into a standardized unit, making it easier to deploy and manage. By the end of this guide, you will have a fully functional FastAPI application running within Docker containers.
Step 1: Set Up Your FastAPI Project
-
Create a New Directory
- Open your terminal and create a new directory for your FastAPI project.
- Navigate into the directory:
mkdir fastapi-docker cd fastapi-docker
-
Initialize a Python Environment
- Set up a virtual environment:
python3 -m venv venv source venv/bin/activate
- Set up a virtual environment:
-
Install FastAPI and Uvicorn
- Install the necessary packages:
pip install fastapi uvicorn
- Install the necessary packages:
-
Create a Simple FastAPI Application
- Create a new file named
main.py
and add the following code:from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"}
- Create a new file named
Step 2: Create a Dockerfile
-
Create the Dockerfile
- In your project directory, create a file named
Dockerfile
with no file extension.
- In your project directory, create a file named
-
Add Instructions to the Dockerfile
- Open the
Dockerfile
and insert the following instructions:FROM python:3.9 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
- Open the
-
Create a requirements.txt File
- Create a
requirements.txt
file and list the dependencies:fastapi uvicorn
- Create a
Step 3: Create a Docker Compose File
-
Create the docker-compose.yml File
- In the same directory, create a file named
docker-compose.yml
.
- In the same directory, create a file named
-
Define Your Service
- Add the following configuration to
docker-compose.yml
:version: '3' services: fastapi: build: . ports: - "8000:8000"
- Add the following configuration to
Step 4: Build and Run Your Application
-
Build the Docker Image
- Use Docker Compose to build your application:
docker-compose build
- Use Docker Compose to build your application:
-
Run the Application
- Start your FastAPI application with the following command:
docker-compose up
- Start your FastAPI application with the following command:
-
Access the Application
- Open your web browser and navigate to
http://localhost:8000
. You should see a JSON response:{"Hello": "World"}
- Open your web browser and navigate to
Conclusion
You have successfully containerized your FastAPI application using Docker and Docker Compose. This setup allows for easy deployment and scalability. As a next step, consider exploring how to add a database or integrate with other services to enhance your application. Happy coding!