๐Ÿ“ Fastapi

Deploying FastAPI with Docker

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
342
๐ŸŒณ
Level
Advanced

This guide runs the FastAPI application and PostgreSQL in separate containers and passes sensitive configuration through environment variables.

Dockerfile

FROM python:3.12-slim

WORKDIR /app

# Dependencies in a separate layer for caching
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

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

requirements.txt

fastapi
uvicorn[standard]
sqlmodel
pyjwt[crypto]
pwdlib[argon2]

.dockerignore

.git
.env
__pycache__
*.pyc
.pytest_cache

docker-compose.yml

version: "3.9"

services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://user:pass@db/mydb
      - SECRET_KEY=${SECRET_KEY}
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: mydb
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user"]
      interval: 5s
      timeout: 5s
      retries: 5

volumes:
  postgres_data:

Running

docker compose up --build
docker compose up -d        # run in background
docker compose logs -f api  # follow logs
docker compose down         # stop

Migrations in Docker

# Add a command in docker-compose.yml
services:
  api:
    command: >
      sh -c "alembic upgrade head && uvicorn main:app --host 0.0.0.0 --port 8000"

Deploying to Railway

# railway.toml
[build]
builder = "dockerfile"

[deploy]
startCommand = "uvicorn main:app --host 0.0.0.0 --port $PORT"

Railway will also automatically detect a Dockerfile if one is present.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Middleware and CORS in FastAPI

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 330
๐Ÿ“

HTTPException in FastAPI

Covered topics: Basic Usage, Status Codes, Error Details, Custom Headers.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 298
๐Ÿ“

Dependency Injection in FastAPI

Depends โ€” FastAPI's dependency injection system for reusing code across endpoints.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 304
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

FastAPI: From First Route to an AI-Powered Site Open course curriculum