A FastAPI project is quick to scaffold, but the documentation examples stop exactly where operations begin: package layout, settings from the environment, a container that does not run as root, and a reverse proxy in front. I installed this boilerplate in a throwaway container on 14 November 2026 and exercised it with real requests. The main finding: without further configuration, fastapi run only honours X-Forwarded-Proto and X-Forwarded-For when the TCP connection comes from loopback, that is from 127.0.0.1 or ::1. A reverse proxy in the neighbouring container does not come from there in the usual bridge network.
Project Skeleton: Router, Models, Dependencies
pyproject.toml with entrypoint
The project consists of pyproject.toml and the package app/ with config.py, deps.py, models.py, main.py and routers/items.py. The dependency is fastapi[standard]. According to the PyPI metadata, the extra brings the fastapi command, Uvicorn with httptools and uvloop (uvloop not on Windows or PyPy), and pydantic-settings. Without the extra, fastapi-cli and Uvicorn are missing, and fastapi run aborts:
RuntimeError: To use the fastapi command, please install "fastapi[standard]":
pip install "fastapi[standard]"
[project]
name = "demo-api"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"fastapi[standard]",
]
[tool.fastapi]
entrypoint = "app.main:app"
The [tool.fastapi] block solves an old annoyance: fastapi run without a path argument finds the app through this entry, even in a package layout. That is exactly what worked in the test, the startup output reports "Using import string: app.main:app".
Separate Input and Output Models
# app/models.py
from pydantic import BaseModel, ConfigDict, Field
class ItemCreate(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=50)
price: float = Field(gt=0)
description: str | None = None
class ItemRead(BaseModel):
id: int
name: str
price: float
description: str | None = None
Two models instead of one, because the response should contain only what the output model defines. The FastAPI docs justify this with the example of a password that would otherwise end up in the response. extra="forbid" departs from the Pydantic default ignore: a client that sends an unknown field receives a 422 response instead of having the field silently dropped.
Settings, Store and Router
# app/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
app_name: str = "Demo API"
environment: str = "production"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
# app/deps.py
from functools import lru_cache
from typing import Annotated
from fastapi import Depends
from .config import Settings
@lru_cache
def get_settings() -> Settings:
return Settings()
SettingsDep = Annotated[Settings, Depends(get_settings)]
class Store:
"""Placeholder for a resource (e.g. a DB connection)."""
def __init__(self) -> None:
self.items: dict[int, dict] = {}
@lru_cache
def get_store() -> Store:
return Store()
StoreDep = Annotated[Store, Depends(get_store)]
@lru_cache on get_settings is the pattern from the settings docs: the .env is read once, and tests can override the dependency. The Store is deliberately demo code, one singleton per process. My first version created it as a yield dependency per request and lost every entry that way, a GET after a POST returned 404.
# app/routers/items.py
from typing import Annotated
from fastapi import APIRouter, HTTPException, Path, Query
from ..deps import StoreDep
from ..models import ItemCreate, ItemRead
router = APIRouter(prefix="/items", tags=["items"])
@router.post("/", status_code=201)
def create_item(payload: ItemCreate, store: StoreDep) -> ItemRead:
item_id = len(store.items) + 1
item = ItemRead(id=item_id, **payload.model_dump())
store.items[item_id] = item.model_dump()
return item
@router.get("/{item_id}")
def read_item(
item_id: Annotated[int, Path(ge=1)],
store: StoreDep,
) -> ItemRead:
if item_id not in store.items:
raise HTTPException(status_code=404, detail="Item not found")
return ItemRead.model_validate(store.items[item_id])
@router.get("/")
def list_items(
store: StoreDep,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
) -> list[ItemRead]:
return [ItemRead.model_validate(v) for v in list(store.items.values())[:limit]]
# app/main.py
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from .deps import SettingsDep
from .routers import items
log = logging.getLogger("uvicorn.error")
@asynccontextmanager
async def lifespan(app: FastAPI):
log.info("lifespan: startup")
yield
log.info("lifespan: shutdown")
app = FastAPI(title="Demo API", lifespan=lifespan)
app.include_router(items.router)
@app.get("/healthz")
def healthz(settings: SettingsDep) -> dict[str, str]:
return {"status": "ok", "env": settings.environment}
@app.get("/whoami")
def whoami(request: Request) -> dict[str, str]:
return {"url": str(request.url), "client": request.client.host}
The handlers are def, not async def. The FastAPI docs are unambiguous here: if you call libraries without await support, which is true for most database drivers, use def, and FastAPI runs the function in a threadpool. Verbatim: "If you just don't know, use normal def." The /whoami endpoint is a diagnostic tool for the proxy test below and gets removed before deployment.
What the Server Answers to Real Requests
Test Environment and Measurements
I tested in a throwaway container from python:3.12-alpine (Python 3.12.13, linux/arm64, 2 CPUs, 1 GB RAM limit) with python -m venv and pip, so deliberately without uv and without the Dockerfile below. Installed were fastapi 0.163.0 (released the same day), fastapi-cli 0.0.34, pydantic 2.14.3, pydantic-settings 2.16.3 and uvicorn 0.54.0. The figures apply to this environment, not to the slim image.
| Measurement | Value | How measured |
|---|---|---|
pip install "fastapi[standard]" pydantic-settings into an empty venv |
40 seconds | timestamps before and after the call |
Size of .venv afterwards |
100.3M |
du -sh .venv, output verbatim |
Idle memory of fastapi run, one process |
69416 kB VmRSS, about 68 MiB | /proc/<pid>/status after the test requests |
All packages arrived as prebuilt wheels for musl/arm64, there was no compiler in the image.
The Responses Verbatim
| Request | Status | Response |
|---|---|---|
GET /healthz |
200 | {"status":"ok","env":"production"} |
POST /items/ with {"name":"Kaffee","price":2.5} |
201 | {"id":1,"name":"Kaffee","price":2.5,"description":null} |
GET /items/99 |
404 | {"detail":"Item not found"} |
GET /items/0 |
422 | greater_than_equal, loc: ["path","item_id"] |
POST /items/ with {"name":"x","price":-1,"foo":1} |
422 | greater_than for price and extra_forbidden for foo |
GET /items/?limit=1000 |
422 | less_than_equal, loc: ["query","limit"] |
The complete 422 response to the last example:
{"detail":[{"type":"less_than_equal","loc":["query","limit"],"msg":"Input should be less than or equal to 100","input":"1000","ctx":{"le":100}}]}
Notable: the input field echoes the invalid input, which for fields with confidential content is a decision you should make consciously. Pydantic offers the option hide_input_in_errors for this; whether it affects FastAPI's 422 body is something I did not check.
Proxy Headers Only Count from 127.0.0.1 and ::1
Three Requests, Three Answers
The Docker page of the FastAPI docs advises: behind Nginx or Traefik, add --proxy-headers. According to the source of fastapi-cli 0.0.34, however, that option is already on by default. What matters is a different setting that the same page does not mention (as of 14 November 2026). I called /whoami with the headers X-Forwarded-Proto: https and X-Forwarded-For: 203.0.113.7, once from 127.0.0.1 and once from the container IP 172.17.0.2:
| Sender of the TCP connection | FORWARDED_ALLOW_IPS |
Response |
|---|---|---|
| 127.0.0.1 | not set | {"url":"https://127.0.0.1:8000/whoami","client":"203.0.113.7"} |
| 172.17.0.2 | not set | {"url":"http://172.17.0.2:8000/whoami","client":"172.17.0.2"} |
| 172.17.0.2 | * |
{"url":"https://172.17.0.2:8000/whoami","client":"203.0.113.7"} |
From loopback the headers take effect, from any other address they are ignored: scheme http, client is the proxy. The cause is in uvicorn/config.py of version 0.54.0: self.forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1,::1"). The Uvicorn docs put it this way: "Defaults to enabled, but is restricted to only trusting connecting IPs in the forwarded-allow-ips configuration."
What That Means in a Container
+----------------+ X-Forwarded-Proto: https +-------------------------------+
| Reverse Proxy | --------------------------> | fastapi run :8000 |
| 172.20.0.2 | X-Forwarded-For: <client> | trusts 127.0.0.1,::1 only |
+----------------+ | -> scheme http, client=proxy |
+-------------------------------+
A reverse proxy in the neighbouring container does not connect from loopback in the usual bridge network with separate network namespaces; only with a shared network namespace, for example through the container:<name> network mode, does the connection arrive from 127.0.0.1. Without FORWARDED_ALLOW_IPS the app builds redirect URLs with http, logs the proxy IP as the client, and a rate limiter sees only the proxy. The variable belongs in the Compose file, not in the Dockerfile, because the value depends on the network. According to the docs, Uvicorn accepts addresses, networks and *. The proxy network already exists in this example, hence external: true; take the subnet from docker network inspect proxy:
services:
api:
build: .
environment:
FORWARDED_ALLOW_IPS: "172.20.0.0/16" # subnet of your proxy network
networks: [proxy]
networks:
proxy:
external: true # existing network the proxy is attached to
According to the FastAPI docs, * trusts all incoming IPs and is only defensible when the proxy alone talks to the server, because anyone who talks to the container directly could claim a foreign client IP. The Uvicorn docs add a further condition: you must be able to trust every value in the forwarded headers, for example because your proxy removes existing headers before setting its own. With *, Uvicorn takes the first entry of X-Forwarded-For, and if the proxy only appends, that entry was set by the client. I tested only *, not the network notation. I compared the two usual candidates in the Caddy versus Traefik comparison, and the wiring with nginx in the post on multiple upstreams behind an nginx container.
The Late 500 from the .env
extra="forbid" Is the Default for BaseSettings
A Pydantic model ignores unknown fields. BaseSettings from pydantic-settings does not do that for .env files: there extra="forbid" applies, and an entry that is not a field in the model raises a ValidationError. This does not apply to plain environment variables, those are simply not picked up. That is why the boilerplate has extra="ignore".
The Server Starts, the First Request Dies
For the test I created a .env with ENVIRONMENT=staging and DATABASE_URL=postgres://x, that is, with a key Settings does not know. With extra="ignore", /healthz answers {"status":"ok","env":"staging"}. Without extra="ignore" the server starts quietly up to "Application startup complete.", and only the first request returns 500 Internal Server Error with this log:
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
database_url
Extra inputs are not permitted [type=extra_forbidden, input_value='postgres://x', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/extra_forbidden
The timing is the treacherous part: get_settings() first runs as a dependency on the first call, so the 500 only shows up then, in the test on /healthz. Until then the container reports a successful start. If you want the error at startup, call get_settings() in the lifespan before the yield. I did not test that, but it follows directly from the flow.
Dockerfile Following the uv Pattern
Multi-Stage, Non-Root, Exec Form
The Dockerfile follows the multistage.Dockerfile from Astral's official example repository and the Docker page of the FastAPI docs. I did not build it on the production server, it is a template: Python and uv versions are adjusted, HEALTHCHECK and EXPOSE are my additions.
# syntax=docker/dockerfile:1
FROM python:3.14-slim-trixie AS builder
COPY --from=ghcr.io/astral-sh/uv:0.13.8 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_NO_DEV=1 \
UV_PYTHON_DOWNLOADS=0
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-install-project
COPY . /app
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked
# Runtime stage: must match the builder, otherwise the Python path in the venv is wrong
FROM python:3.14-slim-trixie
RUN groupadd --system --gid 999 nonroot \
&& useradd --system --gid 999 --uid 999 --create-home nonroot
COPY --from=builder --chown=nonroot:nonroot /app /app
ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1
WORKDIR /app
USER nonroot
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
# Exec form: only this way does SIGTERM reach the process and the lifespan part after yield run
CMD ["fastapi", "run", "--host", "0.0.0.0", "--port", "8000"]
uv sync --locked aborts when uv.lock is missing or does not match pyproject.toml, instead of silently re-resolving. You create that file before the first build with uv lock in the project directory. The runtime image has to match the builder because the path to the Python interpreter in the venv is fixed. python:slim sets no User in its image config, so without a USER instruction of your own the container runs as root, hence groupadd and useradd. The HEALTHCHECK uses urllib instead of curl because curl is not documented as present in the slim image. The one-liner exited with code 0 in the test as long as the server was running. Add .venv, .env and __pycache__ to the .dockerignore. The lifespan part after yield ran after SIGTERM in the test, "lifespan: shutdown" appears in the log before "Finished server process". How start period and restart policy interact is covered in my post on HEALTHCHECK and restart_policy, and the basics of build and runtime stages are in the multi-stage Dockerfile for Node and .NET.
Where I Depart from the Obvious
| Obvious | Chosen | Reason |
|---|---|---|
python:3.14 as in the FastAPI docs |
python:3.14-slim-trixie |
Smaller image: according to Docker Hub only the minimal Debian packages needed for Python, without the packages required to compile extension modules, so a pip install from a source distribution may fail there. |
python:3.14-alpine |
slim | Docker Hub warns about musl instead of glibc. In the test Alpine ran with prebuilt wheels, but there is no such guarantee for every further package |
| Gunicorn with UvicornWorker | fastapi run, one process |
The FastAPI docs deprecated their Gunicorn image and want one process per container; a restart after a crash is the job of the container's restart policy, Uvicorn's own process manager only restarts workers with --workers greater than 1. |
--workers 4 in the container |
one process, several containers | Docs: replication belongs at the cluster level. The exception is a single server with Compose |
--proxy-headers |
FORWARDED_ALLOW_IPS |
The option is already the default; what matters is the allow list, which without the variable holds only 127.0.0.1 and ::1, see the test |
async def everywhere |
def |
Docs rule for libraries without await |
Questions When Reproducing This
Import Path and Python Version
Why does uvicorn main:app report an import error even though the app runs?
Because the app lives in app/main.py. From the project root the message reads verbatim ERROR: Error loading ASGI app. Could not import module "main". Correct is uvicorn app.main:app, or simply fastapi run, which reads the entrypoint.
Which Python version do I need?
fastapi 0.163.0 requires Python 3.11 or newer. Python 3.10 has been unsupported since 1 October 2026, and fastapi 0.162.6 dropped support for it. The boilerplate sets >=3.12, the Dockerfile uses 3.14, which is supported until October 2030 according to the Python Developer's Guide, with security fixes only after the first two years.
Pinning the Version
How do I keep the FastAPI version stable?
Through uv.lock and uv sync --locked. FastAPI releases in quick succession, 0.163.0 appeared on the test day, 0.162.6 with the end of Python 3.10 the day before. Without a lockfile, for example when installing with pip from the dependencies in pyproject.toml, the next build may resolve a newer version. With an unchanged uv.lock the version stays fixed, even without a version bound in pyproject.toml.
Sources and Next Steps
From the Demo Store to a Real Resource
As the next step I replace the Store with a real resource as a yield dependency with finally, once the state no longer lives in the process. If you would rather have such a service operated for you than host it yourself, that is the area I cover under IT support and operations.
Sources Checked
- FastAPI CLI: entrypoint,
fastapi run - FastAPI in Containers: exec form, one process per container
- FastAPI behind a Proxy:
--forwarded-allow-ips - Uvicorn Settings
- Pydantic Settings: dotenv and extra
- Using uv in Docker and the uv-docker-example
Note: The articles on this blog are produced with the help of AI and are editorially reviewed before publication. Editorial responsibility lies with Emre Yurtbay (see the legal notice).