By WebNest Studio Engineering Team
Python Tutorial
Configuring and Deploying FastAPI Applications
An API only becomes useful once it runs somewhere others can reach it. This lesson covers the path from laptop to production: managing configuration with environment variables and pydantic-settings, running with the production server, using multiple worker processes, packaging the app in a Docker image, and the checklist of things to get right — HTTPS, secrets, logging, health checks and database migrations.
Why it matters
An application that only runs on your laptop is not finished. Deployment means configuration that comes from the environment and not from the code, a production server with several workers, and a container that runs the same everywhere. Employers expect a back-end developer to be able to take an API all the way to production.
Configuration with pydantic-settings
Settings that differ between environments — database URL, secret keys, allowed origins, debug flags — belong in environment variables, not in code (the twelve-factor approach). pydantic-settings (pip install pydantic-settings) reads them into a typed, validated BaseSettings class, optionally from a .env file during development. Missing required settings fail fast at start-up, and wrong types are rejected. Never commit .env files containing real secrets.
Running in Production
fastapi run main.py (or uvicorn main:app --host 0.0.0.0 --port 8000) starts the production server without auto-reload. Add --workers 4 to run several processes and use several CPU cores; in Kubernetes, you usually run one process per container and scale the number of containers instead. Put the app behind a reverse proxy or load balancer (Nginx, Traefik, a cloud load balancer) that terminates HTTPS, and pass --proxy-headers so FastAPI sees the real client address and scheme.
Production Checklist
- Secrets from environment variables or a secrets manager; debug off.
- HTTPS everywhere; strict CORS origins.
- Structured logging and a
/healthendpoint for load balancers and orchestrators. - Database migrations (Alembic) run as a deployment step, never create_all() on a live database.
- Pinned dependency versions, a small non-root Docker image, and automated tests in CI.
- Popular hosts: any VPS with Docker, Render, Railway, Fly.io, Google Cloud Run, AWS (ECS, App Runner, Lambda with Mangum) and Azure Container Apps.
Examples
Typed settings from environment variables
# config.py pip install pydantic-settings
import os
from functools import lru_cache
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_prefix="APP_")
app_name: str = "Webnest API"
debug: bool = False
database_url: str = "sqlite:///app.db"
secret_key: str = Field(min_length=32) # required: no default
allowed_origins: list[str] = ["http://localhost:5173"]
@lru_cache # read the environment once
def get_settings() -> Settings:
return Settings()
# Simulating the environment a server would provide:
os.environ["APP_SECRET_KEY"] = "x" * 40
os.environ["APP_DEBUG"] = "true"
os.environ["APP_ALLOWED_ORIGINS"] = '["https://webnest.example"]'
settings = get_settings()
print(settings.app_name, settings.debug, settings.database_url)
print(settings.allowed_origins, len(settings.secret_key))
os.environ["APP_SECRET_KEY"] = "too-short"
try:
Settings()
except Exception as e:
print(type(e).__name__, "-", e.errors()[0]["msg"])
Webnest API True sqlite:///app.db
['https://webnest.example'] 40
ValidationError - String should have at least 32 characters
Production commands
pip freeze > requirements.txt # or use uv / Poetry lock files
fastapi run app/main.py --port 8000 # production server, no reload
fastapi run app/main.py --workers 4 # four worker processes
# Equivalent with Uvicorn directly, behind a reverse proxy:
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4 --proxy-headers
alembic upgrade head # apply database migrations before starting
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started parent process [1]
INFO: Started server process [8]
INFO: Started server process [9]
INFO: Started server process [10]
INFO: Started server process [11]
INFO: Application startup complete.
A Dockerfile for a FastAPI application
# Dockerfile
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["fastapi", "run", "app/main.py", "--port", "8000", "--proxy-headers"]
# Build and run:
# docker build -t webnest-api .
# docker run -p 8000:8000 --env-file .env webnest-api
Successfully tagged webnest-api:latest
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Common Mistakes
- Running fastapi dev / --reload in production.
- Committing .env files or hard-coding secrets in the Docker image.
- Running containers as root and shipping huge images with build tools included.
- Creating tables with create_all() on a production database instead of running migrations.
- Forgetting --proxy-headers behind a proxy, so generated URLs use http instead of https.
Exercise
Using pydantic-settings, which must be installed with pip install pydantic-settings, define a Settings class that reads port and debug from environment variables with the prefix APP_, with defaults of 8000 and False. The code sets one variable, so that value should replace the default while the other stays as it is.
Expected output: 9000 False
import os
from pydantic_settings import BaseSettings, SettingsConfigDict
os.environ["APP_PORT"] = "9000" # normally set outside the program
# TODO: class Settings(BaseSettings) with the prefix APP_,
# port: int = 8000 and debug: bool = False
settings = Settings()
print(settings.port, settings.debug)
Show hints
- The prefix is set with
model_config = SettingsConfigDict(env_prefix="APP_"). - The text "9000" from the environment is converted to an
intbecause of the type hint.
Show solution
import os
from pydantic_settings import BaseSettings, SettingsConfigDict
os.environ["APP_PORT"] = "9000" # normally set outside the program
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="APP_")
port: int = 8000
debug: bool = False
settings = Settings()
print(settings.port, settings.debug)
Quick quiz
1. Where should secrets such as a database password come from in production?
- A. The source code
- B. Environment variables or a secrets manager
- C. A comment in the README
- D. The URL
Show answer
B. Secrets in the code end up in version control and are the same in every environment.
2. Why is the --reload option not used in production?
- A. It is not supported
- B. It disables HTTPS
- C. It watches files and restarts the server, which costs performance and is meant for development
- D. It deletes logs
Show answer
C. Production runs a fixed number of workers with no reloading.
3. What does a Dockerfile describe?
- A. The database schema
- B. The test plan
- C. The API routes
- D. How to build an image containing the application and everything it needs to run
Show answer
D. The same image runs unchanged on a laptop, a test server and in production.
Interview questions
How do you run a FastAPI application in production?
Show answer
Run it with an ASGI server such as Uvicorn, with several worker processes so that all CPU cores are used, behind a reverse proxy or load balancer that terminates HTTPS. Configuration comes from environment variables. The application is usually packaged as a Docker image, and a health-check endpoint lets the platform restart it if it stops responding.
How should configuration be handled across development, testing and production?
Show answer
Keep the code identical in every environment and take everything that differs — database URL, secrets, debug flag, allowed origins — from environment variables. A typed settings class, such as one built on pydantic-settings, reads and validates them at start-up, so a missing or invalid value stops the application immediately with a clear error. A .env file may supply values in development and is never committed.
Key Points to Remember
- Keep configuration in environment variables; pydantic-settings validates it.
- fastapi run (or uvicorn) serves production traffic; --workers uses more CPU cores.
- Terminate HTTPS at a reverse proxy or load balancer.
- Docker packages the app and its dependencies into a reproducible image.
- Add health checks, logging, migrations and CI tests to every deployment.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering