Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Deployment and Customization

Running Streamlit with Docker and a Reverse Proxy

Package a Streamlit app in a Docker image, set options with environment variables, add a health check, and put it behind Nginx with WebSocket support and HTTPS.

When you need your own domain, a bigger machine, private networking or single sign-on, you run Streamlit yourself. The standard approach is a Docker container for the app and a reverse proxy (Nginx, Caddy, Traefik or a cloud load balancer) in front. The container gives you a repeatable environment; the proxy adds HTTPS and routes traffic.

Streamlit has one unusual requirement that causes most deployment pain: it talks to the browser over a WebSocket, not just plain HTTP requests. Anything between the user and your app must allow WebSocket connections and keep them open. This lesson shows a Dockerfile, how to configure the server, and the proxy settings that keep the connection alive.

Docker and servers cannot run on this site, so the files below are read-only. The TryIt builds the STREAMLIT_* environment variables for a container from a settings dictionary, which is the part you can check in Python.

A Dockerfile

DOCKERFILE
FROM python:3.12-slim

ENV PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1

WORKDIR /app

# Install dependencies first so Docker can cache this layer
COPY requirements.txt .
RUN pip install -r requirements.txt

# Then copy the code
COPY . .

# Run as a normal user, not root
RUN useradd --create-home appuser
USER appuser

EXPOSE 8501

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8501/_stcore/health')"

ENTRYPOINT ["streamlit", "run", "app.py", \
            "--server.port=8501", "--server.address=0.0.0.0", "--server.headless=true"]

Why each part is there:

  • Slim base image. Smaller downloads and fewer packages to patch. Use the Python version your app was developed against.
  • Requirements before code. Docker caches each layer. If only your code changes, the pip install layer is reused and rebuilds take seconds, not minutes.
  • Non-root user. If someone finds a way to run code inside the container, they are not root.
  • --server.address=0.0.0.0. Inside a container the app must listen on all interfaces, otherwise the published port cannot reach it.
  • --server.headless=true. Do not try to open a browser or ask for an email address on startup.
  • Health check. Streamlit exposes /_stcore/health, which answers ok when the server is alive. Orchestrators use it to restart a stuck container.

Add a .dockerignore so the build does not send junk into the image, and above all so secrets are never baked into it:

Text
.git
.venv
__pycache__
.streamlit/secrets.toml
*.env
data/raw/

Build and run:

Terminal
docker build -t my-dashboard .
docker run --rm -p 8501:8501 --env-file .env my-dashboard

Configuration through environment variables

You rarely want different images for different environments. Instead, set options through the environment (the rules from Configuration and Themes): server.maxUploadSize becomes STREAMLIT_SERVER_MAX_UPLOAD_SIZE. Secrets can be passed the same way, by reading os.environ in the app, or by mounting a secrets.toml file as a read-only volume.

Python Build an env file for a container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep this file out of git if it contains secrets, or keep two files: public settings in the Compose file and private values in .env.

Docker Compose with a proxy

Compose describes several containers together. This example runs the app and Nginx, with Nginx as the only service that publishes ports:

YAML
services:
  app:
    build: .
    restart: unless-stopped
    env_file: .env
    expose:
      - "8501"          # reachable by other containers, not from the internet

  proxy:
    image: nginx:1.27-alpine
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on:
      - app

Only the proxy faces the internet. The app container is reachable only inside the Compose network, which reduces what an attacker can reach directly.

The reverse proxy and WebSockets

Streamlit's browser connection is a WebSocket at the path /_stcore/stream. A proxy that does not forward the Upgrade header breaks the app with a spinner that never ends or a "connecting" banner. A working Nginx configuration:

NGINX
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name dashboard.example.com;
    return 301 https://$host$request_uri;
}

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

    ssl_certificate     /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;

    client_max_body_size 50m;          # match server.maxUploadSize

    location / {
        proxy_pass http://app:8501;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        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_read_timeout 86400;      # keep idle WebSockets open
    }
}

The lines that matter most:

  • proxy_http_version 1.1 plus the Upgrade and Connection headers make WebSockets work.
  • proxy_read_timeout 86400 stops Nginx from closing a connection that is quiet for a minute (the default), which would otherwise show users a disconnected page whenever they pause.
  • client_max_body_size must be at least server.maxUploadSize, or uploads fail with a 413 error before Streamlit sees them.
  • Certificates come from your CA, for example a free Let's Encrypt certificate renewed automatically. Caddy and Traefik can obtain and renew certificates for you with less configuration.

Serving under a sub-path

To host at https://example.com/dashboard/ instead of a whole domain, set server.baseUrlPath=dashboard and proxy that location to the app. The path must match on both sides, and the WebSocket path moves with it.

Scaling and sessions

Each browser session holds a WebSocket and some server memory, and Python runs your script in a thread per session. Practical consequences:

  • One Streamlit process uses one CPU effectively for your Python code (because of the GIL), so heavy compute in the script delays other users. Move heavy work out of the app (a queue, a database, a precomputed file).
  • If you run several app containers behind a load balancer, a session must keep talking to the same one, because session state lives in that process's memory. Configure sticky sessions (affinity), for example ip_hash or a cookie-based option in Nginx.
  • Caches are per process. Two containers each have their own cache_data, so a shared cache or database does better for large setups.
  • Estimate memory as base usage plus per-session state, times the number of concurrent sessions. Set container memory limits and let the orchestrator restart on out-of-memory.

Operating it

  • Logs: Streamlit writes to standard output; let Docker collect it (docker logs). Do not print secrets.
  • Updates: rebuild the image, test it, and replace the container. Connected users reconnect and start a new session, since session state is lost.
  • Backups: the container is disposable. Back up the database and storage it uses, not the container.
  • Monitoring: watch the health endpoint, memory and restart counts.
  • Authentication: newer Streamlit versions support OpenID Connect login (st.login) through configuration. Otherwise put an authenticating proxy (OAuth2 Proxy, your cloud's identity-aware proxy) in front. Do not rely on a hidden URL.

Common mistakes

  • Binding to 127.0.0.1 inside the container, so the port is unreachable.
  • A proxy that drops WebSocket upgrades, giving an endless spinner.
  • The default proxy read timeout closing idle connections.
  • Baking secrets.toml into the image (add it to .dockerignore).
  • Running several containers without sticky sessions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a Streamlit app behind Nginx show an endless spinner if Upgrade headers are missing?

    The browser and the Streamlit server communicate over a WebSocket. The proxy must forward the Upgrade and Connection headers.
  2. 2. Why copy requirements.txt and run pip install before copying the rest of the code in a Dockerfile?

    Layers are cached in order. Dependencies change rarely, so placing them first keeps rebuilds fast.
  3. 3. Which setting makes the app reachable from outside a container?

    Binding to all interfaces lets the published port reach the app. 127.0.0.1 would only accept connections from inside the container.
  4. 4. Why use sticky sessions with several Streamlit containers?

    Each process holds its own session state. Without affinity, requests can land on a container that does not know the session.

Summary

  • Package the app with a slim Python image, dependencies first, a non-root user and a health check on /_stcore/health.
  • Listen on 0.0.0.0 and run headless inside the container; configure through STREAMLIT_* environment variables.
  • Put a reverse proxy in front for HTTPS and make sure it forwards WebSocket upgrades and has a long read timeout.
  • Match client_max_body_size to server.maxUploadSize; keep secrets out of the image.
  • Plan for per-process memory and caches, and use sticky sessions when you run several containers.

Next: Performance and Security Checklist