Python

Deploying FastAPI with Docker, Nginx, and HTTPS: A Production Guide

Building a FastAPI application locally is usually the easy part. You install the dependencies, write a few endpoints, start Uvicorn, and everything works as…

D
DevByteTechnical Author
Published
15 min read3 views
Deploying FastAPI with Docker, Nginx, and HTTPS: A Production Guide

Building a FastAPI application locally is usually the easy part. You install the dependencies, write a few endpoints, start Uvicorn, and everything works as expected.

Things become more interesting when you need to make that application available to real users.

You need a reliable way to run the application, handle incoming traffic, configure a domain, enable HTTPS, manage environment variables, and restart the service when something goes wrong. You also need a deployment process that lets you update your application without manually rebuilding everything from scratch.

One practical approach is to combine FastAPI, Docker, Nginx, and Let's Encrypt.

In this guide, we'll deploy a working FastAPI application using Docker Compose. Nginx will act as a reverse proxy, Docker will manage the application container, and Certbot will help configure HTTPS certificates.

We'll also cover environment variables, container security, logging, troubleshooting, and a few production considerations that are easy to overlook when deploying your first Python API.

1. Understanding the Deployment Architecture

Before writing configuration files, let's understand how the components work together.

Our deployment will use four main components:

  • FastAPI: Handles application logic and API requests.

  • Uvicorn: Runs the FastAPI application as an ASGI server.

  • Docker: Packages the application and its dependencies into a container.

  • Nginx: Receives incoming HTTP and HTTPS requests and forwards them to FastAPI.

  • Certbot and Let's Encrypt: Provide and renew HTTPS certificates.

The request flow looks like this:

                  Client / Browser
                         |
                         | HTTPS :443
                         v
                  +--------------+
                  |     Nginx    |
                  | Reverse Proxy|
                  +--------------+
                         |
                         | HTTP :8000
                         v
                  +--------------+
                  |    Uvicorn   |
                  |   FastAPI    |
                  +--------------+
                         |
                         v
                  Database / External APIs

In this setup, Nginx is the public entry point. The FastAPI container does not need to expose its application port directly to the internet.

This separation provides several benefits.

Nginx can handle TLS termination, request forwarding, and certain HTTP-level controls. FastAPI focuses on application logic, while Docker provides a consistent environment for running the application.

For a small application, this architecture is often enough to get started. Larger deployments might introduce a load balancer, multiple application replicas, centralized logging, and a managed database.

2. Create a FastAPI Application

Let's begin with a simple API that we can deploy and test.

Create a project directory:

mkdir fastapi-production
cd fastapi-production

mkdir app

Your initial project structure will look like this:

fastapi-production/
├── app/
│   └── main.py
├── requirements.txt
├── Dockerfile
├── compose.yaml
└── .dockerignore

Create app/main.py:

from fastapi import FastAPI
from datetime import datetime, timezone

app = FastAPI(
    title="Production FastAPI",
    version="1.0.0",
)


@app.get("/")
async def root():
    return {
        "message": "FastAPI is running",
    }


@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "timestamp": datetime.now(
            timezone.utc
        ).isoformat(),
    }


@app.get("/api/users")
async def get_users():
    return {
        "users": [
            {"id": 1, "name": "Rahul"},
            {"id": 2, "name": "Priya"},
        ]
    }

This application provides three endpoints:

Endpoint

Purpose

/

Confirms that the application is running

/health

Provides a basic health response

/api/users

Returns sample user data

The health endpoint is useful for checking whether the application responds to requests. In a real application, you might also implement a separate readiness check that verifies required dependencies, such as a database connection.

Avoid making a basic liveness endpoint depend on every external service. Otherwise, a temporary database outage could cause an orchestrator to restart otherwise healthy application processes unnecessarily.

3. Define the Python Dependencies

Create requirements.txt:

fastapi
uvicorn[standard]

These are the only packages required for our sample application.

For a production project, pin tested dependency versions or use a dependency lockfile so that rebuilding the image doesn't unexpectedly install incompatible releases.

You can run the application locally before moving on:

pip install -r requirements.txt

uvicorn app.main:app --reload

Open the following paths in your browser:

  • http://127.0.0.1:8000/

  • http://127.0.0.1:8000/health

  • http://127.0.0.1:8000/docs

The /docs endpoint provides FastAPI's interactive API documentation.

The reload option is useful during development, but it should not be used as a production deployment strategy.

4. Create a Production-Ready Dockerfile

Docker allows you to package your application with the Python runtime and required dependencies.

Create a file named Dockerfile in the project root:

FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /app

RUN addgroup --system appgroup \
    && adduser --system --ingroup appgroup appuser

COPY requirements.txt .

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

COPY app ./app

RUN chown -R appuser:appgroup /app

USER appuser

EXPOSE 8000

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

Let's examine the important parts.

Use a lightweight base image

FROM python:3.12-slim

The slim image contains a smaller set of operating system packages than the full Python image.

A smaller image can reduce transfer time and storage requirements. However, some Python packages need additional operating system libraries to compile or run, so you might need to install extra dependencies.

Prevent unnecessary Python files

ENV PYTHONDONTWRITEBYTECODE=1

This prevents Python from writing .pyc files during normal imports.

The following setting makes Python output unbuffered:

ENV PYTHONUNBUFFERED=1

Unbuffered output is helpful when collecting application logs through Docker.

Run as a non-root user

USER appuser

Running the application as a non-root user reduces the privileges available to the application process if it is compromised.

This doesn't replace other security measures, but it is a sensible default for production containers.

Bind to the correct network interface

"--host",
"0.0.0.0"

Inside a container, binding Uvicorn to 127.0.0.1 would make it inaccessible through the container's network interface.

Binding to 0.0.0.0 allows the application to receive connections through the container network.

Important: Binding to 0.0.0.0 inside the container does not mean you must expose the application port publicly on the host. We'll configure networking separately using Docker Compose.

5. Exclude Unnecessary Files with .dockerignore

Create .dockerignore:

.git
.gitignore
.venv
venv
__pycache__
*.py[cod]
.pytest_cache
.mypy_cache
.ruff_cache
.env
.env.*
!.env.example
.coverage
htmlcov
dist
build

This prevents unnecessary files from being copied into the Docker build context.

For example, your local virtual environment might contain hundreds of megabytes of files that the production container doesn't need.

Excluding .env files also reduces the risk of accidentally including secrets in the image.

Remember that .dockerignore is not a substitute for secret management. Don't pass production credentials through Docker build arguments or embed them into image layers.

6. Configure Docker Compose

Docker Compose allows you to define the services that make up your application in a single configuration file.

Create compose.yaml:

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    expose:
      - "8000"
    environment:
      APP_ENV: production
    networks:
      - backend

networks:
  backend:
    driver: bridge

Let's understand this configuration.

The API service

api:
  build:
    context: .
    dockerfile: Dockerfile

Docker Compose builds the application image using the Dockerfile in the current directory.

Restart policy

restart: unless-stopped

Docker attempts to restart the container if it exits unexpectedly, subject to the restart policy and Docker daemon availability.

This is useful for recovering from some process failures, but it doesn't replace monitoring, alerting, or application-level error handling.

Expose the application port internally

expose:
  - "8000"

This makes the intended container port visible to other services on the Docker network without publishing it as a host port.

When we add Nginx, it will connect to the API through the internal Docker network.

Unlike a configuration using ports:, this setup doesn't directly publish port 8000 on the server.

7. Add Nginx as a Reverse Proxy

Nginx receives incoming requests and forwards them to the FastAPI application.

It can also handle HTTPS certificates, redirect HTTP traffic to HTTPS, and apply request-level controls.

Create an nginx directory:

mkdir nginx
mkdir -p certbot/www
mkdir -p certbot/conf

Update the project structure:

fastapi-production/
├── app/
│   └── main.py
├── nginx/
│   └── conf.d/
│       └── app.conf
├── certbot/
│   ├── conf/
│   └── www/
├── requirements.txt
├── Dockerfile
├── compose.yaml
└── .dockerignore

Create nginx/conf.d/app.conf:

server {
    listen 80;
    server_name api.example.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        proxy_pass http://api:8000;

        proxy_http_version 1.1;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_connect_timeout 10s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

Replace api.example.com with your actual domain or subdomain.

Understanding proxy_pass

proxy_pass http://api:8000;

The hostname api refers to the API service name in Docker Compose.

Docker's internal DNS resolves the service name to the container's address on the shared network.

You should not use localhost:8000 here. Inside the Nginx container, localhost refers to the Nginx container itself, not the FastAPI container.

Forward the original request information

These headers pass information about the original client request to FastAPI:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

They can be useful for logging, redirects, and generating absolute URLs.

However, forwarded headers should be trusted only when they come through a proxy you control. Don't configure Uvicorn to trust arbitrary forwarded headers from untrusted clients.

8. Update Docker Compose to Include Nginx

Now update compose.yaml so that Nginx becomes the public entry point.

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    expose:
      - "8000"
    environment:
      APP_ENV: production
    networks:
      - backend

  nginx:
    image: nginx:stable
    restart: unless-stopped
    depends_on:
      - api
    ports:
      - "80:80"
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./certbot/www:/var/www/certbot:ro
    networks:
      - backend

networks:
  backend:
    driver: bridge

The Nginx service publishes port 80 on the server, while the FastAPI service remains accessible only through the Docker network.

The depends_on setting controls service startup order, but it does not guarantee that FastAPI is ready to accept requests when Nginx starts.

For more robust deployments, configure health checks and an appropriate readiness strategy.

Start the containers

Run:

docker compose up -d --build

Check their status:

docker compose ps

View the application logs:

docker compose logs -f api

For Nginx logs:

docker compose logs -f nginx

At this stage, your API should be accessible over HTTP once DNS and firewall settings are correct.

9. Configure Your Domain and Firewall

Before requesting an HTTPS certificate, make sure your domain points to your server.

For a typical deployment, configure a DNS A record:

Type: A
Name: api
Value: YOUR_SERVER_PUBLIC_IP

If you use a DNS provider that supports proxying, such as Cloudflare, ensure its configuration is compatible with your certificate issuance and renewal method.

For this guide, we'll use the HTTP-01 challenge, which requires the certificate authority to reach your server over port 80.

Open the required ports

Your server firewall and hosting provider's firewall should allow inbound traffic on:

  • TCP port 80 for HTTP and certificate validation.

  • TCP port 443 for HTTPS.

SSH should also be available for administration, ideally restricted to trusted IP addresses where practical.

You generally do not need to expose port 8000 publicly.

On Ubuntu with UFW, you can check the firewall status:

sudo ufw status

If UFW is enabled, allow web traffic using:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Make sure your SSH access remains permitted before changing firewall rules remotely.

10. Enable HTTPS with Let's Encrypt and Certbot

HTTPS encrypts traffic between clients and your server. It helps protect credentials, tokens, and API data from being read or modified in transit.

Let's Encrypt provides certificates that can be renewed automatically.

For this setup, Certbot will request a certificate using the HTTP-01 challenge.

Step 1: Start Nginx with the HTTP configuration

Make sure your Nginx configuration contains the ACME challenge location:

location /.well-known/acme-challenge/ {
    root /var/www/certbot;
}

This maps a request such as:

http://api.example.com/.well-known/acme-challenge/token

to a file under:

/var/www/certbot/.well-known/acme-challenge/token

Start or reload the services:

docker compose up -d --build

Step 2: Request the certificate

Replace the sample domain and email address with your own values.

docker compose run --rm certbot certonly \
  --webroot \
  --webroot-path /var/www/certbot \
  --email admin@example.com \
  --agree-tos \
  --no-eff-email \
  -d api.example.com

This command requires a certbot service in your Compose configuration. Add the following service before running it:

  certbot:
    image: certbot/certbot
    volumes:
      - ./certbot/conf:/etc/letsencrypt
      - ./certbot/www:/var/www/certbot

Because the Certbot service uses the same challenge directory as Nginx, the certificate authority can retrieve the validation file.

After successful issuance, the certificate files will be available under:

certbot/conf/live/api.example.com/

The directory contains files such as:

fullchain.pem
privkey.pem

The private key must remain confidential.

If certificate issuance fails, verify DNS resolution, port 80 accessibility, the Nginx configuration, and the challenge path before retrying.

11. Configure Nginx for HTTPS

After obtaining the certificate, update nginx/conf.d/app.conf to support both HTTP and HTTPS.

server {
    listen 80;
    server_name api.example.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name api.example.com;

    ssl_certificate
        /etc/letsencrypt/live/api.example.com/fullchain.pem;

    ssl_certificate_key
        /etc/letsencrypt/live/api.example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;

    location / {
        proxy_pass http://api:8000;

        proxy_http_version 1.1;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_connect_timeout 10s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

This configuration does two things:

  1. Redirects ordinary HTTP requests to HTTPS.

  2. Terminates TLS connections on port 443 and forwards requests to FastAPI over the private Docker network.

The certificate paths must match the files created by Certbot.

Mount the certificate directory into Nginx

Update the Nginx service in compose.yaml:

  nginx:
    image: nginx:stable
    restart: unless-stopped
    depends_on:
      - api
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./certbot/www:/var/www/certbot:ro
      - ./certbot/conf:/etc/letsencrypt:ro
    networks:
      - backend

Reload the deployment:

docker compose up -d

Validate the Nginx configuration:

docker compose exec nginx nginx -t

If the configuration is valid, reload Nginx:

docker compose exec nginx nginx -s reload

Now test the HTTPS endpoint:

curl -i https://api.example.com/health

You should receive an HTTP response from your FastAPI application over HTTPS.

12. Automate Certificate Renewal

Let's Encrypt certificates have a limited validity period, so renewal must be part of your deployment process.

Add a renewal service to compose.yaml:

  certbot:
    image: certbot/certbot
    volumes:
      - ./certbot/conf:/etc/letsencrypt
      - ./certbot/www:/var/www/certbot

You can test the renewal process using:

docker compose run --rm certbot renew --dry-run

A dry run checks whether the renewal process can succeed without replacing the active certificate.

For an actual deployment, schedule renewal using a host cron job or systemd timer. For example, a cron job could run twice daily:

0 3,15 * * * cd /opt/fastapi-production && docker compose run --rm certbot renew --quiet && docker compose exec -T nginx nginx -s reload

Adjust /opt/fastapi-production to the directory where you deploy the project.

This command attempts renewal and reloads Nginx afterward. A reload helps Nginx begin using renewed certificate files without stopping the service.

Test the full renewal and reload procedure before relying on it in production. Also monitor certificate expiration, because a scheduled command alone does not guarantee successful renewal.

13. Manage Environment Variables and Secrets

Real FastAPI applications usually need database credentials, API keys, and other environment-specific configuration.

Avoid hardcoding secrets into source files or Docker images.

For example, update your Compose configuration:

services:
  api:
    build: .
    restart: unless-stopped
    expose:
      - "8000"
    environment:
      APP_ENV: production
      DATABASE_URL: ${DATABASE_URL:?DATABASE_URL must be set}
      SECRET_KEY: ${SECRET_KEY:?SECRET_KEY must be set}
    networks:
      - backend

You can provide these variables through your deployment environment or a protected environment file.

For example, a local .env file might contain:

DATABASE_URL=postgresql://app_user:password@db:5432/app_db
SECRET_KEY=replace-with-a-long-random-secret

This is only an illustrative configuration. Don't use these placeholder credentials in production.

Keep .env out of version control and restrict access to any file containing secrets. For higher-security environments, consider a dedicated secrets manager.

Also remember that environment variables may be visible to users with sufficient access to the Docker host or container configuration. They are convenient configuration inputs, not a complete secrets-security solution.

14. Add Health Checks and Improve Reliability

A container that is running is not necessarily healthy.

The application might be unable to connect to its database or could be stuck while processing requests.

Docker Compose supports health checks:

services:
  api:
    build: .
    restart: unless-stopped
    expose:
      - "8000"
    healthcheck:
      test:
        - CMD
        - python
        - -c
        - "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s
    networks:
      - backend

This check sends a request to the local health endpoint from inside the container.

If the check repeatedly fails, Docker marks the container as unhealthy.

A health check does not automatically restart every unhealthy container. The restart policy generally responds to container termination, not health status alone. Use monitoring and an appropriate orchestration or recovery strategy if automatic recovery from an unhealthy state is required.

For production systems, also consider:

  • Structured application logs.

  • Request IDs for tracing errors.

  • Database connection pooling.

  • Request timeouts.

  • Graceful shutdown behavior.

  • Metrics and alerts.

  • Backups for persistent data.

  • Regular security updates.

These measures become increasingly important as traffic and application complexity grow.

15. Deploy Updates Without Rebuilding Everything Manually

Once the application is running, you'll need a repeatable deployment process.

For a basic deployment, you can rebuild the image and restart the services:

git pull

docker compose up -d --build

Check the service status:

docker compose ps

Review recent logs:

docker compose logs --tail=100 api

Test the health endpoint:

curl -f https://api.example.com/health

This is a simple deployment workflow, not a zero-downtime deployment guarantee. Recreating a single API container can interrupt requests while the application restarts.

For a more mature setup, build images in CI, tag them with a commit identifier, push them to a container registry, and deploy a known image version. Multiple application replicas behind a load balancer can help support rolling deployments when the infrastructure and application are designed for them.

Avoid relying on the latest tag as your only way to identify a production image. Explicit version tags make rollbacks and incident investigation easier.

16. Common Deployment Problems and How to Fix Them

Even a straightforward Docker deployment can fail for reasons that are not immediately obvious.

Problem 1: Nginx returns 502 Bad Gateway

A 502 usually means Nginx couldn't obtain a valid response from the upstream service.

Check the application logs:

docker compose logs api

Check whether the API container is running:

docker compose ps

Verify that the upstream address is correct:

proxy_pass http://api:8000;

Make sure the API service is on the same Docker network as Nginx and that Uvicorn is listening on 0.0.0.0:8000 inside the container.

Problem 2: The HTTPS certificate cannot be issued

Check that:

  • The domain resolves to the correct public IP.

  • Port 80 is accessible from the internet.

  • Nginx serves the ACME challenge from the expected directory.

  • The domain is spelled correctly.

  • No other service is intercepting the challenge request.

You can inspect DNS records using tools such as dig:

dig +short api.example.com

Problem 3: FastAPI generates incorrect redirects

If FastAPI needs to know that the original request used HTTPS, configure trusted proxy headers carefully.

Uvicorn supports proxy-header handling, but you should trust forwarded headers only from known proxy addresses.

For example, Uvicorn offers the --proxy-headers and --forwarded-allow-ips options. Configure the allowed proxy IPs according to your actual network topology rather than trusting arbitrary clients.

Problem 4: The application works locally but fails inside Docker

Common causes include missing dependencies, incorrect file paths, unavailable environment variables, and attempts to connect to services through localhost.

Remember that localhost inside a container refers to that container. For another service in the same Compose network, use its service name.

Problem 5: The application stops after a server restart

Check that Docker is enabled at system startup and that your Compose services have suitable restart policies.

Also verify that required files, mounted volumes, and configuration are available after the host restarts.

Conclusion

Deploying FastAPI with Docker, Nginx, and HTTPS gives you a practical foundation for running Python APIs in production.

Docker packages the application and its dependencies. Nginx provides a public reverse-proxy entry point, while Let's Encrypt supplies HTTPS certificates. Docker Compose ties these services together so you can manage the deployment through a single configuration.

But getting the API online is only the beginning. A production-ready service also needs secure secret management, reliable certificate renewal, health monitoring, useful logs, dependency updates, and a deployment strategy that matches its availability requirements.

Start with a simple architecture, test each component independently, and add complexity only when your application needs it. A deployment that is easy to understand, monitor, and recover is often more valuable than one with unnecessary infrastructure.

Further Reading

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘