OneBite.Dev - Coding blog in a bite size

FastAPI and PostgreSQL docker compose setup (simple version)

Here is how my minimal setup for fastAPI and PostgreSQL project using docker-compose for local development

Here is how I currently setup my FastAPI project that requires Postgres using docker-compose.

Please also refer to Tiangolo’s docker setup

Folder structure

Here is how my folder structure looks like

- Project
  |_ src
    | _ main.py
      _ requirements.txt
  |_ docker-compose.yml
  | _ Dockerfile 

I wrap all code related in src folder. The minimal version only has one main.py
and one requirements.txt file

Main.py

Simple server for FastAPI

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
  return {"Hello": "World"}

requirements.txt (optional)

This is optional, you can create empty file for now and later use it as you need it

Dockerfile

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9

WORKDIR /app

COPY ./src /app/src
COPY ./src/requirements.txt /app/

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

Docker Compose file

version: '3.8'

services:
  web:
    build: .
    command: uvicorn src.main:app --host 0.0.0.0 --reload
    volumes:
      - ./src:/app/src
    ports:
      - "8000:8000"
    depends_on:
      - db
    environment:
      - DATABASE_URL=postgresql://username:password@db:5432/fastapi_db

  db:
    image: postgres:13
    environment:
      - POSTGRES_USER=username
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=fastapi_db
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Now try to access your app from http://localhost:8000

fastapi docker