Setting Up Docker for Local Development with PostgreSQL and FastAPI
In today's fast-paced development environment, setting up a consistent and reproducible development environment is crucial. Docker has emerged as a powerful tool for achieving this, allowing developers to create, deploy, and run applications in containers. If you’re a FastAPI enthusiast and need a PostgreSQL database for your projects, this guide will walk you through setting up Docker for local development, ensuring you can focus on building your application without the hassle of configuration issues.
Understanding Docker and Its Benefits
Docker is a platform that uses containerization technology to package applications and their dependencies into isolated environments. This approach has several advantages:
- Consistency: Docker ensures that your application runs the same way in development, testing, and production environments.
- Isolation: Each container runs independently, preventing conflicts between applications.
- Scalability: Docker simplifies the scaling of applications, enabling easy management of multiple instances.
Using Docker with FastAPI and PostgreSQL not only enhances your development workflow but also streamlines deployment. Let’s dive into how to set this up.
Prerequisites
Before getting started, ensure you have the following installed on your machine:
- Docker: Download and install from Docker's official website.
- Docker Compose: This comes bundled with Docker Desktop, but verify it's available by running
docker-compose --version
in your terminal. - Python: Ensure you have Python 3.6 or higher installed.
Step 1: Create Your Project Structure
Start by creating a directory for your FastAPI application. Open your terminal and run:
mkdir fastapi-postgres-docker
cd fastapi-postgres-docker
Inside this directory, create the following structure:
fastapi-postgres-docker/
│
├── app/
│ ├── main.py
│ └── requirements.txt
├── Dockerfile
└── docker-compose.yml
Step 2: Define Your FastAPI Application
In the app/requirements.txt
file, specify the necessary dependencies:
fastapi
uvicorn
asyncpg
databases
Next, create a simple FastAPI application in app/main.py
:
from fastapi import FastAPI
import databases
import sqlalchemy
DATABASE_URL = "postgresql://user:password@db/postgres"
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
app = FastAPI()
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.get("/")
async def read_root():
return {"message": "Welcome to FastAPI with PostgreSQL!"}
Step 3: Create the Dockerfile
The Dockerfile
defines how your FastAPI application will be built. Here’s a simple Dockerfile:
# Use the official Python image.
FROM python:3.9
# Set the working directory in the container.
WORKDIR /app
# Copy the requirements file.
COPY app/requirements.txt .
# Install the dependencies.
RUN pip install --no-cache-dir -r requirements.txt
# Copy the FastAPI application into the container.
COPY app .
# Command to run the FastAPI application.
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
Step 4: Set Up Docker Compose
Docker Compose will help manage your multi-container application. Create a docker-compose.yml
file with the following content:
version: '3.8'
services:
db:
image: postgres:latest
environment:
POSTGRES_DB: postgres
POSTGRES_USER: user
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
fastapi:
build: .
ports:
- "8000:8000"
depends_on:
- db
Explanation of the docker-compose.yml file:
- db: This service uses the official PostgreSQL image and sets up the database with default credentials.
- fastapi: This service builds the FastAPI application from the Dockerfile and binds it to port 8000.
Step 5: Build and Run Your Application
You’re now ready to build and run your application. Open your terminal in the fastapi-postgres-docker
directory and execute:
docker-compose up --build
This command will build the Docker image for FastAPI and start both the FastAPI and PostgreSQL containers. You should see logs indicating that both services have started successfully.
Step 6: Testing Your Setup
Open your web browser and navigate to http://localhost:8000
. You should see the message:
{"message": "Welcome to FastAPI with PostgreSQL!"}
You can also access the interactive API documentation by going to http://localhost:8000/docs
.
Troubleshooting Tips
If you encounter issues, consider the following:
- Check Docker Logs: Use
docker-compose logs
to view logs for both services. - Database Connection Errors: Ensure your database URL in
main.py
matches the credentials set indocker-compose.yml
. - Rebuild Containers: If you make changes to the Dockerfile or dependencies, run
docker-compose up --build
again.
Conclusion
Setting up Docker for local development with PostgreSQL and FastAPI can save you time and frustration, allowing you to focus on building great applications. By following this guide, you’ve created a robust development environment that is easy to scale and maintain. As you continue to develop your application, feel free to explore more advanced configurations, such as adding migrations with Alembic or deploying to a production environment using Docker Swarm or Kubernetes. Happy coding!