DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

Dockerizing a FastAPI App: Eliminating "It Works on My Machine"

What is Docker?

Docker packages your app and all its dependencies
into a container a lightweight, portable unit that
runs exactly the same on any machine.

No more "it works on my machine" problems.

The Dockerfile

FROM python:3.11-slim

WORKDIR /app

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

COPY . .

EXPOSE 8000

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

Line by line:

  • FROM → base image (Python 3.11)
  • WORKDIR → working directory inside container
  • COPY requirements.txt → copy dependencies first
  • RUN pip install → install dependencies
  • COPY . . → copy all app code
  • EXPOSE 8000 → open port 8000
  • CMD → command to start the app

docker-compose.yml

services:
  api:
    build: .
    ports:
      - "8000:8000"
    command: python -m uvicorn main:app --host 0.0.0.0 --port 8000
Enter fullscreen mode Exit fullscreen mode

Docker Compose links services together
useful when you add a database container later.

Build & Run

docker build -t gdgoc-bowen-api.
docker-compose up --build

Proof it Builds

docker build

Lessons Learned

Docker is not just a DevOps tool, it's a
backend developer's best friend. Every production
app runs in containers today. Learning Docker
early puts you ahead of most developers.

Day 19 done. 11 more to go.

GDGoCBowen30dayChallenge

Top comments (0)