Skip to content

Deploy to production

On this page you create shop at the production level, run it in containers and check it before you ship. You learn how FastAPI reads settings per environment, how the OAuth2 password flow with JWT tokens protects an endpoint, what a middleware does (here: a request id and structured logs), and how FastAPI runs in a container with /health and /ready probes. You also meet fastkit's production bundle, the migrate service of its Docker Compose file and fastkit doctor.

Create the project

The production level is the domain level with a bundle of features. As on the previous page, use a folder where no shop exists yet:

$ fastkit init --level production --name shop --no-venv -y
...
│ Features        │ Authentication: JWT; Testing: Coverage; Migrations:        │
│                 │ Alembic; Developer tooling: ruff, github-actions; Logging: │
│                 │ structured; Deployment: Docker, docker-compose             │
...
$ cd shop
$ ls -A
.dockerignore       Dockerfile      pyproject.toml
.env            README.md       requirements-dev.txt
.env.example        alembic         requirements.txt
.gitattributes      alembic.ini     scripts
.github         conftest.py     src
.gitignore      docker-compose.yml  tests

Next to the items domain, src/app/domains/ has an auth domain, and src/app/logging_config.py sets up the logs. README.md describes each feature under "Selected features".

Settings and secrets

src/app/core/config.py reads the settings from environment variables and from .env; an environment variable wins over the same name in .env. fastkit wrote .env with a unique key (SECRET_KEY=...), and Git ignores .env. The key signs the access tokens below, so it must stay secret. The setting ENVIRONMENT is development, staging or production, and outside development the app refuses to start with a weak key:

$ uv sync -q
$ env ENVIRONMENT=production SECRET_KEY=too-short uv run uvicorn src.app.main:app
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
  Value error, SECRET_KEY must be at least 32 bytes when ENVIRONMENT=production. Generate one with `python -c "import secrets; print(secrets.token_urlsafe(32))"` and set it as SECRET_KEY in the environment or .env. [type=value_error, input_value={'ENVIRONMENT': 'producti...ECRET_KEY': 'too-short'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.14/v/value_error

Run it in containers

A container image holds your app with Python and its packages, so it runs the same wherever Docker runs. The Dockerfile describes the image:

Dockerfile
# The image starts from the official slim Python image and adds the app on top.
# https://fastapi.tiangolo.com/deployment/docker/
FROM python:3.12-slim
# ...
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# ...
CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8000"]

docker-compose.yml starts three services: postgres (the database), migrate (runs alembic upgrade head once, then exits) and app, which starts only after the database is healthy and the migration succeeded. Every revision in alembic/versions/ then runs against that database, so read and test an autogenerated revision before it gets there: Alembic sees a renamed column, for example, as a dropped column plus a new one.

$ docker compose up --build -d
...
 ✔ Container shop-postgres-1    Healthy6.7s
 ✔ Container shop-migrate-1     Exited7.6s
 ✔ Container shop-app-1         Started7.7s
$ curl -s http://127.0.0.1:8000/health
{"status":"ok"}
$ curl -s http://127.0.0.1:8000/ready
{"status":"ok"}

/health answers as long as the process runs; the image's HEALTHCHECK calls it. /ready also checks the database and answers 503 when it is unreachable, so a platform that runs containers can send traffic only to a ready one. The containers read .env too. It sets ENVIRONMENT=development, which wins over the image's ENVIRONMENT=production, so docker compose up runs the app in development mode; the README and the comments in docker-compose.yml say so. For production mode, add ENVIRONMENT=production under environment: of the app service (entries there win over .env) and recreate the app:

docker-compose.yml
    environment:
      - DATABASE_URL=postgresql+asyncpg://${POSTGRES_USER:-user}:${POSTGRES_PASSWORD:-password}@postgres:5432/${POSTGRES_DB:-dbname}
      - ENVIRONMENT=production
$ docker compose up -d
...
$ docker compose exec app printenv ENVIRONMENT
production

Warning

The database user, password and name default to user, password and dbname. docker-compose.yml reads them as ${POSTGRES_USER:-user}, ${POSTGRES_PASSWORD:-password} and ${POSTGRES_DB:-dbname}, from the shell or from .env, both for the postgres service and for the DATABASE_URL of app and migrate. Set them before the first docker compose up: PostgreSQL creates the account only when its volume is empty. Changed later, they change only what the app sends, and it can no longer connect; then change the account inside PostgreSQL, or remove the volume with docker compose down -v, which deletes the data.

ENVIRONMENT=production does not encrypt the traffic, and the requests below send a password and a token. Before you expose the app, put a proxy or a platform in front of it that terminates HTTPS; see About HTTPS.

Protect an endpoint

In the OAuth2 password flow, a client sends an email address and a password to a token endpoint and receives an access token. This flow suits the application's own clients, such as its own web page or mobile app; clients of other parties use another flow, such as the authorization code flow. A JWT access token is a signed string that names the user and an expiry time. The client sends it back in the Authorization: Bearer <token> header, and the server checks the signature with SECRET_KEY. In src/app/domains/auth/dependencies.py, a dependency turns the header into the signed-in user:

src/app/domains/auth/dependencies.py
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/token")

TokenDep = Annotated[str, Depends(oauth2_scheme)]
# ...
async def get_current_user(token: TokenDep, users: UserRepositoryDep) -> User:
    """Resolve the bearer token into a live, active account."""
# ...
CurrentUser = Annotated[User, Depends(get_current_user)]

OAuth2PasswordBearer reads the token from the header and answers 401 when it is missing; it also gives Swagger UI at /docs its Authorize button. get_current_user checks the token and loads the account, or answers 401. An endpoint that declares current_user: CurrentUser runs only for a signed-in user, as GET /api/v1/users/me does. Register, get a token (the token endpoint reads a form, not JSON, and username carries the email) and call the endpoint without and with the token (put the access_token value in a shell variable first: TOKEN=...). The last request also sends its own request id:

$ curl -s -X POST http://127.0.0.1:8000/api/v1/auth/register -H "Content-Type: application/json" -d '{"email": "ada@example.com", "password": "correct-horse-battery"}'
{"id":1,"email":"ada@example.com","full_name":null,"is_active":true}
$ curl -s -X POST http://127.0.0.1:8000/api/v1/auth/token -d "username=ada@example.com" -d "password=correct-horse-battery"
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwidHlwZSI6ImFjY2VzcyIsImlhdCI6MTc5NjMxNzM5NiwiZXhwIjoxNzk2MzE5MTk2fQ.Jkd-gVyg3b9HxgmWbR3-BdraUWRhw826EzDFjlEfifg","token_type":"bearer","expires_in":1800}
$ curl -s -i http://127.0.0.1:8000/api/v1/users/me
HTTP/1.1 401 Unauthorized
...
x-request-id: b6354ce0dfad4b76acb25d2f128f2cb2

{"detail":"Not authenticated"}
$ curl -s -i http://127.0.0.1:8000/api/v1/users/me -H "Authorization: Bearer $TOKEN" -H "X-Request-ID: ada-1"
HTTP/1.1 200 OK
...
x-request-id: ada-1

{"id":1,"email":"ada@example.com","full_name":null,"is_active":true}

Swagger UI of the production shop with the Authorize dialog for OAuth2PasswordBearer open, username and password filled in, and GET /api/v1/users/me behind it

Logs and middleware

A middleware is code that runs around every request: before the endpoint and after the response. src/app/logging_config.py adds one that gives each request an id (the client's own X-Request-ID, or a new random one) and returns it in the X-Request-ID header, as in the responses above:

src/app/logging_config.py
# A middleware runs around every request: this one tags it and its logs with an id.
# https://fastapi.tiangolo.com/tutorial/middleware/
class RequestIDMiddleware(BaseHTTPMiddleware):
    """Attach an id to every request and expose it on the response."""

    async def dispatch(
        self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
    ) -> Response:
        request_id = request.headers.get(REQUEST_ID_HEADER) or uuid.uuid4().hex
        # ...
        response.headers[REQUEST_ID_HEADER] = request_id
        return response

In between, await call_next(request) lets the endpoint answer, and the middleware then writes one access line for the request. The same file writes every log line as one JSON object, which log tools can search by field:

$ docker compose logs app
...
shop-app-1  | {"timestamp": "2026-12-03T17:03:16+0000", "level": "INFO", "logger": "app.access", "message": "GET /api/v1/users/me 401", "request_id": "b6354ce0dfad4b76acb25d2f128f2cb2", "method": "GET", "path": "/api/v1/users/me", "status_code": 401, "duration_ms": 0.51, "client": "192.168.176.1"}
shop-app-1  | {"timestamp": "2026-12-03T17:03:16+0000", "level": "INFO", "logger": "app.access", "message": "GET /api/v1/users/me 200", "request_id": "ada-1", "method": "GET", "path": "/api/v1/users/me", "status_code": 200, "duration_ms": 3.51, "client": "192.168.176.1"}

The middleware sets the id before call_next and clears it after the access line. Lines that your endpoints and dependencies log in between carry the id, and so does the access line, so you can find the lines of one request by the X-Request-ID a client reports. uvicorn's traceback for an unhandled exception is written after that and shows "request_id": "-"; the access line of that request (status 500) has the id.

Continuous integration

.github/workflows/test.yml runs on every push to main and on every pull request on GitHub. After installing requirements-dev.txt it runs the commands below. Before you push, uv run bash scripts/lint.sh runs black, isort, mypy and ruff check, and uv run pytest the tests; the generated project passes them all, as well as ruff format --check . (101 tests):

.github/workflows/test.yml
      - name: Lint
        run: |
          ruff check .
          ruff format --check .

      - name: Run tests
        run: pytest

Before you ship

fastkit doctor checks a generated project for known problems, such as a .env committed to Git or an example SECRET_KEY. Some checks need a Git repository:

$ git init -q
$ git add .
$ fastkit doctor
...
┃Check                 ┃ Status  ┃ Severity ┃ Details                          ┃
┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│env-tracked           │ ok      │ -        │ No .env file is committed to git │
...
╭────────────── Success ───────────────╮
│ ✨ No problems found.                │
╰──────────────────────────────────────╯

It exits with status 1 when a problem remains, so a CI job can run it too. Check and fix a project shows how it fixes what it finds. When you are done, docker compose down -v --rmi local stops the containers and removes them, the database volume and the app image.

FastAPI documentation

Next

The Learn track ends here. The How-to guides cover single tasks, starting with Choose a level or an example, and the CLI reference lists every command and option.