📝 Fastapi

Deploying FastAPI with Docker

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
76
🌳
Level
Advanced

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

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
python-jose[cryptography]
passlib[bcrypt]

.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

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 120
📝

run_in_executor and anyio: Sync Libraries in Asyn…

Sometimes you need to call a synchronous library from async code without blocking the event...

📅 30.06.2026 👁️ 99
📝

Async Context Managers: async with and @asynccont…

Async context managers manage resources in async code — connections, files, transactions.

📅 30.06.2026 👁️ 106

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!