FastAPI-ontwikkelomgeving met Docker

Voorbeeld van de opzet van een ontwikkelomgeving voor FastAPI met Docker.

Projectstructuur

.
├── app
│   ├── __init__.py
│   └── main.py
├── docker-compose.yml
├── Dockerfile
└── requirements.txt

App

# __init__.py kan een leeg bestand zijn
# main.py

from typing import Union

from fastapi import FastAPI

app = FastAPI()


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


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

Basic FastAPI-bestand

Dockerfile

# Select an python image appropriate for your project
FROM python:3.9-slim

# Upgrade pip (optional)
RUN /usr/local/bin/python -m pip install --upgrade pip

# Create directory "/app" and use it as working directory
WORKDIR /app

# Set env variables to improve build and debugging
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Install dependencies as root
COPY requirements*.txt ./
RUN pip install --no-cache-dir --upgrade -r requirements.txt

# Run app as a general user worker
RUN useradd -m worker
USER worker

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

Content of Dockerfile.dev

Opdrachtregel

De broncode van de applicatie zelf nemen we niet in het image op. Het image is statisch en bedoeld als onderdeel van een ontwikkelomgeving. De applicatiecode voegen aan de container toe als een volume gekoppeld op /app.

De FastAPI-applicatie in ontwikkeling kan nu eenvoudig gestart worden met de volgende opdrachtregel.

docker run --volume ./app:/app --rm (docker build -q .)

Verwijzingen

PYTHONDONTWRITEBYTECODE and PYTHONUNBUFFERED Explained
Introduction Have you ever come across the enigmatic environment variables PYTHONDONTWRITEBYTECODE and PYTHONUNBUFFERED in Python Dockerfiles and wondered about their significance? These two variables frequently surface in the Docker ecosystem and we…