StreamlitPython

Deploy a Streamlit app

Run a Streamlit app in production from its own Dockerfile, with a health check on /_stcore/health, WebSockets through the platform and managed Postgres for shared data. This guide takes app.py to a live deploy on Modelence.

Last updated /Tested with Streamlit 1.67.0, SQLAlchemy 2.1.9 and Python 3.12.3

To deploy a Streamlit app, start it with streamlit run app.py --server.port=$PORT --server.address=0.0.0.0 --server.headless=true in a container, point the platform's health check at /_stcore/health and make sure the browser's WebSocket reaches the server. Modelence, a managed cloud on AWS, builds that image from your Dockerfile and keeps the container running in any of 17 regions, with managed MongoDB, Postgres and Redis beside it, all from one deploy command.

Streamlit turns a Python script into an interactive web app: every click reruns the script, and the page talks to the server over a WebSocket that stays open while the tab is. That makes hosting it a little different from a plain web API, because each user's session lives in the server process. This guide builds a small Streamlit app that saves notes to a SQL database and summarizes uploaded CSV files, then covers the start command, the Dockerfile, modelence.config.json, secrets, login with st.login and the deploy. If you already have a Streamlit app, skip to Run the app locally.

Streamlit on Modelence at a glance

How Streamlit runs
streamlit run in a container built from your Dockerfile, on PORT and 0.0.0.0, with headless mode on
Health check
An HTTP check on /_stcore/health, which answers ok once Streamlit can accept browser connections
WebSockets
The page's WebSocket goes through the platform over HTTPS, and Streamlit pings it every 30 seconds
Sessions
One container holds every user's session, and st.cache_resource shares models and clients between them
Databases
Managed MongoDB, Postgres and Redis in the app's region. st.connection reads Postgres from DATABASE_URL
Regions and backups
Pick any of 17 AWS regions. Production databases there get a backup at least every 6 hours
Price
Free plan to try it. Postgres and Redis are on paid plans, from $20 a month with $20 of usage included

Before you start

  • Python 3.11 or newer, which current Streamlit releases require
  • Docker, if you want to build and run the image locally first (optional)
  • Node.js, for running npx modelence. The Streamlit app runs without it
  • A free Modelence account. The managed Postgres used here runs on a paid plan
  • Optionally, a coding agent such as Claude Code, Cursor or Codex to set up the files and deploy for you

Create a Streamlit app

Make a project folder with a virtual environment, and install Streamlit together with SQLAlchemy and the psycopg driver, which the app uses to talk to Postgres once it runs in the cloud:

mkdir team-notes && cd team-notes
python3 -m venv .venv
source .venv/bin/activate
pip install streamlit sqlalchemy "psycopg[binary]"
pip freeze > requirements.txt

requirements.txt now pins each package at the version you installed, and the image will install exactly those. The app is a shared notes page with a CSV summarizer. Notes go to a SQL database through st.connection, so every visitor sees the same list, and an uploaded CSV is summarized by a function under st.cache_data, so a file that was already summarized is answered from the cache.

app.py
import io
import os

import pandas as pd
import streamlit as st
from sqlalchemy import text

st.title("Team notes")

# DATABASE_URL points at the managed Postgres once deployed.
# On your machine, a SQLite file stands in for it.
conn = st.connection("sql", type="sql", url=os.environ.get("DATABASE_URL", "sqlite:///local.db"))


@st.cache_resource
def create_table():
    # Runs once per process, not on every rerun.
    with conn.session as s:
        s.execute(text("CREATE TABLE IF NOT EXISTS notes (body TEXT NOT NULL, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"))
        s.commit()


create_table()

with st.form("add", clear_on_submit=True):
    body = st.text_input("Note")
    if st.form_submit_button("Add") and body:
        with conn.session as s:
            s.execute(text("INSERT INTO notes (body) VALUES (:body)"), {"body": body})
            s.commit()

# ttl=0 reads the table on every rerun, so each user sees new notes at once.
st.dataframe(conn.query("SELECT body, created FROM notes ORDER BY created DESC LIMIT 20", ttl=0))


@st.cache_data(max_entries=20)
def summarize(data: bytes) -> pd.DataFrame:
    return pd.read_csv(io.BytesIO(data)).describe()


uploaded = st.file_uploader("CSV to summarize", type="csv")
if uploaded:
    st.dataframe(summarize(uploaded.getvalue()))

Run the app locally

During development, start the app the usual way:

streamlit run app.py

Streamlit serves it on http://localhost:8501. Without DATABASE_URL the notes go to a SQLite file, local.db, so you can add a note and see it in the table right away.

Then run the command the container will run. It takes the port from PORT, which Modelence sets to the service's main port, listens on all interfaces instead of localhost only, and runs headless, so Streamlit doesn't try to open a browser or ask for an email address on first start:

export PORT=8501
streamlit run app.py --server.port=$PORT --server.address=0.0.0.0 --server.headless=true

From a second terminal, curl http://localhost:8501/_stcore/health prints ok. Streamlit answers that route with a 200 once it can take browser connections and with a 503 while it is starting or shutting down, so the platform's health check can use it.

To run the app on your machine with a Modelence environment's database and variables, connect the project with npx modelence@latest setup, then start it with npx modelence@latest dev, which runs the service's dev command from Describe the app in modelence.config.json with that environment's values.

Keep secrets in environment variables

Read API keys and passwords with os.environ, which behaves the same on your machine and in a deployed container. Streamlit helps on the local side: when it starts, it copies every top-level key of .streamlit/secrets.toml into os.environ, so a local file like this one makes os.environ["OPENAI_API_KEY"] work without exporting anything:

# .streamlit/secrets.toml, on your machine only
OPENAI_API_KEY = "sk-..."

Keep that file out of Git and out of the image, which the .dockerignore below takes care of. In the cloud, the same name is declared as a secret in modelence.config.json and its value is set in the dashboard, where you can view or change it later and every view is logged.

Code that reads st.secrets["OPENAI_API_KEY"] can switch to os.environ, or the container can write secrets.toml from environment variables when it starts. Login with st.login needs the second approach, since its settings must be in the file, and Production readiness shows the script for it.

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

Streamlit keeps each user's widget values in that user's session, so anything all users should share, such as saved records or the output of a long job, belongs in a database. Modelence runs managed MongoDB, Postgres and Redis in the app's region. Each one reaches the app as a connection string in an environment variable, traffic to it uses TLS, and production databases are backed up at least every six hours.

For Postgres, st.connection("sql", type="sql", url=...) accepts the URL directly, so the app passes os.environ["DATABASE_URL"] and needs no [connections.sql] block in secrets.toml. The URL looks like postgresql://...?sslmode=require, and SQLAlchemy 2.1 opens a postgresql:// URL with psycopg 3, so it works unchanged. With SQLAlchemy 2.0, write the scheme as postgresql+psycopg://. Streamlit creates the engine once per process, and all sessions share its connection pool. Two things to know about the connection:

  • conn.query() caches results through st.cache_data, and without ttl they stay cached until the process restarts. Pass ttl=0 for tables users write to, and something like ttl=600 for reports that may be ten minutes old.
  • Writes go through conn.session, a SQLAlchemy session, and need s.commit().

For Redis, build the client inside a function marked st.cache_resource, so every session uses one connection pool. The URL starts with rediss://, which redis-py turns into a TLS connection on its own:

@st.cache_resource
def get_redis():
    return redis.from_url(os.environ["REDIS_URL"])

For MongoDB, add "db": { "type": "mongodb" } to resources and create pymongo.MongoClient(os.environ["MONGODB_URI"]) the same way. An existing Postgres on Supabase or Neon also works: declare its URL in env as a secret and pass that variable to st.connection.

The table in this guide is created by CREATE TABLE IF NOT EXISTS once per process. When the schema starts to change between releases, apply Alembic migrations to the environment's database ahead of each deploy rather than at container start.

In modelence.config.json, both databases sit under resources, and a deploy provisions any that don't exist yet before it starts the new version:

modelence.config.json
{
  "resources": {
    // "web": the Streamlit service, as in the next steps
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "cache": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
  }
}

Write a Dockerfile

Python apps on Modelence are built from their own Dockerfile. Put this one in the project root, next to app.py:

  • FROM pulls the slim Python image through public.ecr.aws/docker/library/, the AWS mirror of Docker Hub's official images, which keeps builds clear of Docker Hub's pull limits.
  • Packages install from requirements.txt in their own layer before the code is copied, so editing app.py reuses the installed packages on the next build.
  • CMD uses the shell form so that $PORT expands, and exec replaces the shell with Streamlit, so the stop signal goes straight to it. In our test Streamlit exited about 1.5 seconds after SIGTERM.
  • --server.address=0.0.0.0 lets the load balancer and the health check reach Streamlit from outside the container.

Add a .dockerignore beside it, so the virtual environment, the local SQLite file and local secrets never reach the image:

.git
.venv
__pycache__
local.db
.streamlit/secrets.toml
Dockerfile
FROM public.ecr.aws/docker/library/python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD exec streamlit run app.py --server.port=$PORT --server.address=0.0.0.0 --server.headless=true

Describe the app in modelence.config.json

Commit modelence.config.json at the repository root with the app and the Dockerfile:

  • web is built from the Dockerfile and listens on 8501, Streamlit's usual port, which the container also gets as PORT. As the first service, it receives the environment's URL on the first deploy.
  • healthCheck sends requests to /_stcore/health, so a new container gets traffic only after Streamlit answers there with a 200 within 4 seconds.
  • dev runs when you start the app on your machine with npx modelence@latest dev.
  • main-db is the Postgres database, whose URL reaches the app as DATABASE_URL.
modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "web": {
      "type": "service",
      "dockerfile": "Dockerfile",
      "ports": [8501],
      "healthCheck": { "type": "http", "path": "/_stcore/health" },
      "dev": { "commands": ["streamlit run app.py --server.port=8501"] }
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" }
  }
}

Adjust the config for your project

  • If the entry file has another name, such as streamlit_app.py or the Home.py of a multipage app, change it in CMD and in dev. Pages in a pages/ folder next to it are picked up as usual.
  • Match the FROM tag to the project's Python version, 3.11 or later for current Streamlit.
  • Settings that don't depend on the environment can go in .streamlit/config.toml, committed with the app, such as a [theme] or maxUploadSize under [server]. Flags on the command line win over the file. To turn off the usage statistics Streamlit collects in the browser, add gatherUsageStats = false under [browser].
  • Packages that need system libraries, such as a geospatial stack built on GDAL, get them from an apt-get install line in the Dockerfile before pip install.
  • Declare API keys with "type": "secret" and no value. The deploy asks for any that are missing, and you can change them later under Environment variables in the dashboard.
  • For an app in a subdirectory of a repository, such as dashboard/, set "root": "dashboard" on the service. The build context and the dockerfile path then start from that folder.

Check the build locally

If you have Docker, build the image and start it with the port a deploy passes in:

docker build -t team-notes .
docker run --rm -e PORT=8501 -p 8501:8501 team-notes

http://localhost:8501/_stcore/health should answer ok, and http://localhost:8501 should load the page and connect. Right after the page loads, the browser opens a WebSocket to /_stcore/stream, and the app's content arrives over it. A deploy builds the same Dockerfile, so a broken build shows up here first.

Deploy

From the project directory, run:

npx modelence@latest deploy

A browser tab opens where you sign in, choose or create the organization, app and environment, and fill in any variables the environment is missing. The command then uploads the project, builds the image and streams the build until the new version is healthy. An environment's region is chosen on its first deploy, out of 17 AWS regions, and its container and database run there.

On the first deploy, Modelence creates the Postgres database, starts web once it is ready and serves it at <app>-<environment>.cloud.modelence.app over HTTPS. The browser's WebSocket uses the same address. Streamlit pings it every 30 seconds, well within the load balancer's 300-second idle timeout, so a tab left open for hours stays connected. Custom domains are added under Domains in the dashboard.

When a later deploy replaces the container, open tabs reconnect to the new version by themselves and run the script again. st.session_state starts over at that point, while everything in Postgres stays as it was.

Let your coding agent do it

Paste Deploy using https://modelence.com/skill.md into Claude Code, Cursor or Codex with the project open. From the docs at that link, the agent writes the Dockerfile and modelence.config.json for this app, tries the build, runs the deploy and hands control back to you for any step that needs your account.

Production readiness

Run one container and give it room

Streamlit keeps each session in the memory of the process that served the page: widget values, st.session_state, files from st.file_uploader and the media behind st.image. This setup runs web as a single container and sizes it under Configure in the dashboard, where containers go up to 4 vCPU and 16 GB of memory. Every session runs its script in its own thread, so one container serves many people at the same time.

Two caches keep memory flat as more people arrive:

  • st.cache_resource keeps one shared object per process, such as a loaded model, a database client or a large read-only DataFrame. Every session gets that same object, so treat it as read-only.
  • st.cache_data stores results serialized and hands each caller a fresh copy. Bound it with ttl and max_entries, or cap all of it with maxCacheDataSize under [server] in .streamlit/config.toml, for example "1gb".

Anything that should outlive a session or a deploy, such as saved results or user preferences, goes to Postgres or Redis.

Keep uploaded files in a bucket

st.file_uploader holds uploads in memory for the length of the session, up to 200 MB per file by default, and the container's own disk is replaced on every deploy. To keep a file, write it to an S3-compatible bucket, such as Amazon S3 or Cloudflare R2, with boto3:

import boto3


@st.cache_resource
def get_s3():
    # boto3 reads AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from the environment.
    # S3_ENDPOINT_URL is only needed for R2 and other S3-compatible stores.
    return boto3.client("s3", endpoint_url=os.environ.get("S3_ENDPOINT_URL"))


if uploaded:
    get_s3().upload_fileobj(uploaded, os.environ["S3_BUCKET"], f"uploads/{uploaded.file_id}/{uploaded.name}")

Declare the two keys as secrets in env, and the bucket name and endpoint as plain variables.

Sign users in with st.login

Streamlit has OpenID Connect login built in. st.login() sends the user to a provider such as Google, Microsoft Entra ID, Okta or Auth0, and afterwards st.user holds their name and email. Add streamlit[auth] to requirements.txt for the Authlib package it needs. The settings go in an [auth] section of .streamlit/secrets.toml, and since the values live in environment variables here, a short script writes that section when the container starts:

# write_secrets.py
# Writes .streamlit/secrets.toml from environment variables at container start.
import json
import os
from pathlib import Path

# SITE_URL is the environment's address. Set AUTH_REDIRECT_URI for a custom domain.
redirect_uri = os.environ.get("AUTH_REDIRECT_URI") or os.environ["SITE_URL"].rstrip("/") + "/oauth2callback"
auth = {
    "redirect_uri": redirect_uri,
    "cookie_secret": os.environ["AUTH_COOKIE_SECRET"],
    "client_id": os.environ["AUTH_CLIENT_ID"],
    "client_secret": os.environ["AUTH_CLIENT_SECRET"],
    "server_metadata_url": os.environ["AUTH_SERVER_METADATA_URL"],
}
lines = ["[auth]"] + [f"{key} = {json.dumps(value)}" for key, value in auth.items()]
Path(".streamlit").mkdir(exist_ok=True)
Path(".streamlit/secrets.toml").write_text("\n".join(lines) + "\n")

Run it in front of Streamlit in the Dockerfile's last line:

CMD python write_secrets.py && exec streamlit run app.py --server.port=$PORT --server.address=0.0.0.0 --server.headless=true

In env, declare AUTH_CLIENT_ID, AUTH_CLIENT_SECRET and AUTH_COOKIE_SECRET with "type": "secret", and give AUTH_SERVER_METADATA_URL the provider's discovery URL as its value, such as https://accounts.google.com/.well-known/openid-configuration. Register the environment's URL followed by /oauth2callback as a redirect URI with the provider. For a custom domain, register that domain's /oauth2callback instead and set it in AUTH_REDIRECT_URI, declared with "required": false. Then put the check at the top of app.py:

if not st.user.is_logged_in:
    st.button("Log in", on_click=st.login)
    st.stop()

Leave CORS and XSRF protection on

Streamlit's defaults, with server.enableCORS and server.enableXsrfProtection both on, work behind the Modelence load balancer as they are, because the page, its WebSocket and file uploads all come from one origin and reach one process. Change them only for a setup that needs it, such as embedding the app in an iframe on another domain, where server.xsrfCookieSameSite = "none" is the smaller change. To choose which hostnames may open a WebSocket, list them in server.allowedHosts, including the environment's hostname and your own domains.

Keep tracebacks in the logs

Streamlit's server messages and anything the script prints or logs go to standard output, which shows on the environment's Logs page, unbuffered thanks to PYTHONUNBUFFERED=1. By default an exception also shows its full traceback in the browser. For an app other people use, set showErrorDetails = "type" under [client] in .streamlit/config.toml, so users see only the exception type and a generic message while the traceback goes to the logs.

Modelence vs Streamlit Community Cloud, Hugging Face Spaces and Render

Streamlit apps are usually weighed between Streamlit Community Cloud, Hugging Face Spaces and a general host such as Render. Prices and limits in the table were taken from each platform's docs and pricing pages in November 2026.

PlatformHow Streamlit runsWhen idlePricing
ModelenceYour Dockerfile's image runs as a container in any of 17 AWS regions, beside managed MongoDB, Postgres and RedisPaid plans keep the container running. The free plan's one instance sleeps when idleFree plan, and paid plans from $20 a month, all of it counted toward usage
Streamlit Community CloudDeploys from a GitHub repository, with up to 2 CPU cores and 2.7 GB of memory per app (limits its docs list as of February 2024)Apps without traffic for 12 hours go to sleepFree for public apps, with one private app at a time
Hugging Face SpacesA Space using the Streamlit SDK, built from a Git repository and served on port 8501Free CPU Basic hardware sleeps after 48 hours without visitors, and upgraded hardware runs until you set a sleep timeCPU Basic (2 vCPU, 16 GB) has no hourly cost, and CPU Upgrade (8 vCPU, 32 GB) costs $0.03 an hour
RenderA web service with your start command on the native Python runtime or from a Dockerfile, in 5 regions (Oregon, Ohio, Virginia, Frankfurt and Singapore)Free web services spin down after 15 idle minutes and take about a minute to start againWorkspace plan (Hobby free, Pro $25 a month) plus instances from $7 a month for 512 MB

Community Cloud is the simplest way to put a public Streamlit app online at no cost, straight from GitHub. Hugging Face Spaces suits a demo built around a model on the Hub, with large free CPU hardware, and Render charges a fixed monthly price per instance with a choice of five regions. Modelence fits a Streamlit app a team relies on every day: signed in through st.login, next to its own Postgres or Redis, running all the time in a region you pick out of 17, with a coding agent able to write the config and run the deploy. Render alternatives and Railway vs Render compare general-purpose hosts in more depth.

Next steps

Frequently asked questions

How do I deploy a Streamlit app?

Start it with streamlit run app.py and three server flags: --server.port set to the port the platform assigns, --server.address=0.0.0.0 so traffic from outside the container reaches it, and --server.headless=true. With Modelence, that command goes in the Dockerfile's CMD, modelence.config.json names the service, its /_stcore/health check and the database, and npx modelence@latest deploy builds the image and starts it on AWS.

Should I use Streamlit Community Cloud or host the app myself?

Community Cloud is free for public apps and deploys straight from GitHub, which works well for demos and open data apps. Its docs list one private app at a time, up to 2.7 GB of memory per app and sleep after 12 hours without traffic. Hosting it yourself fits an app that a team signs in to, needs more memory or a database next to it, or has to run in a specific region. Modelence runs it in the AWS region you choose, out of 17, beside managed MongoDB, Postgres and Redis.

How do I add authentication to a Streamlit app?

Use st.login, Streamlit's built-in OpenID Connect login, with a provider such as Google, Microsoft Entra ID, Okta or Auth0. Install streamlit[auth], put the client ID, client secret, cookie secret, discovery URL and a redirect URI ending in /oauth2callback in the [auth] section of secrets.toml, and check st.user.is_logged_in at the top of the script. On Modelence, keep those values as secrets and write the file from them when the container starts, as this guide shows.

How much memory does a Streamlit app need?

The example app with pandas used about 165 MB in our test with one session open. Each visitor adds their own session state and their own copies of st.cache_data results, so memory grows with the number of users and the size of the data they load. Share large read-only objects through st.cache_resource, bound st.cache_data with ttl and max_entries, and choose a larger container type when needed. Modelence containers go up to 4 vCPU and 16 GB of memory.

How do I connect a Streamlit app to a database?

Use st.connection with type="sql" and pass the URL from the environment, as in st.connection("sql", type="sql", url=os.environ["DATABASE_URL"]). It wraps SQLAlchemy, caches query results through st.cache_data and shares one connection pool between sessions. On Modelence, a managed Postgres declared in modelence.config.json reaches the app as DATABASE_URL, and MongoDB and Redis work through PyMongo and redis-py clients created inside st.cache_resource.

How do I serve a Streamlit app to more users?

Streamlit keeps each session in the process that serves it, so you grow the app by giving that process more room: a larger container type under Configure, up to 4 vCPU and 16 GB, with heavy objects shared through st.cache_resource and slow queries cached with st.cache_data. Data that every user reads or writes goes to Postgres or Redis, which keeps the app process light.

Do I need to disable CORS or XSRF protection behind a proxy?

No. On Modelence the page, its WebSocket and file uploads all come from the same origin, so Streamlit's default enableCORS and enableXsrfProtection settings work as they are. Changing them is only needed for setups such as embedding the app in an iframe on another domain, where setting server.xsrfCookieSameSite to none is the smaller change.

Where do files uploaded to a Streamlit app go?

st.file_uploader keeps uploaded files in the server's memory for the user's session, up to 200 MB per file by default, which server.maxUploadSize changes. They are released after the session ends. To keep a file, write it to an S3-compatible bucket such as Amazon S3 or Cloudflare R2 with boto3, and declare the bucket's keys as secrets.

Can I use my own domain for a Streamlit app?

Yes, add it under Domains in the dashboard and attach it to the web service. Paid plans include unlimited custom domains, served over HTTPS, and the WebSocket works on them the same way. If the app uses st.login, register the domain's /oauth2callback URL with your identity provider and set it as AUTH_REDIRECT_URI.

How much does it cost to host a Streamlit app on Modelence?

The free plan is enough to try it, with one instance that sleeps when idle. Managed Postgres and Redis come with paid plans, starting at $20 a month, and that $20 counts as cloud usage, so you pay extra only past it.

Deploy other stacks

Deploy your Streamlit app

Start on the free plan and move up when your app needs more.

Or paste this into your coding agent