AWS Builder Center

Containerizing FastAPI & PostgreSQL: A Step-by-Step Guide with Docker Compose

Learn how to package a FastAPI web API and a PostgreSQL database into isolated Docker containers, orchestrating them seamlessly using Docker Compose.

Introduction

One of the biggest challenges in software development is ensuring that an application runs exactly the same on a local development machine as it does when deployed to a cloud server (like AWS EC2).
This is where Docker and Docker Compose become essential tools. By containerizing your application and database, you eliminate "it works on my machine" errors and streamline your deployment pipelines.
In this guide, we will step through containerizing a Python FastAPI backend and a PostgreSQL database, linking them together securely.



Step 1: Writing the FastAPI Dockerfile

First, we need to define how to build our FastAPI application image. To keep the final image size small, we'll use a multi-stage build. This separates the build dependencies from the final running container.
Create a file named  Dockerfile  in your backend directory:
# Stage 1: Build dependencies
FROM python:3.10-slim as builder

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential libpq-dev && \
rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

# Stage 2: Final minimal image
FROM python:3.10-slim as runner

WORKDIR /app

RUN apt-get update && apt-get install -y libpq-dev && rm -rf /var/lib/apt/lists/*

# Copy installed libraries and code from builder stage
COPY --from=builder /root/.local /root/.local
COPY . .

ENV PATH=/root/.local/bin:$PATH
EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

version: '3.8'
services:

PostgreSQL Database Service

db: image: postgres:15-alpine container_name: postgres_db restart: always environment: POSTGRES_USER: app_user POSTGRES_PASSWORD: secure_password_123 POSTGRES_DB: app_database volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432" networks: - app-network

FastAPI Backend Service

backend: build: ./backend container_name: fastapi_backend restart: always ports: - "8000:8000" environment: - DATABASE_URL=postgresql://app_user:secure_password_123@db:5432/app_database depends_on: - db networks: - app-network
volumes: postgres_data:
networks: app-network: driver: bridge
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article