Deploy Streamlit¶
Deploy or debug a Streamlit application. Covers local development, Streamlit Community Cloud, Docker, and systemd service setups. Handles environment-aware database connections, caching, and layout best practices.
How It Works¶
- Verify locally -- Run
streamlit run app.py --server.headless trueand confirm the app loads without errors. - Pre-deployment checks -- Validate that all imports are in
requirements.txt, no hardcoded local paths exist, and secrets are stored properly. - Deploy -- Push to the appropriate target:
- Streamlit Community Cloud: Push to GitHub, connect at
share.streamlit.io - Local systemd service: Generate a service file for persistent hosting
- Docker: Generate a
Dockerfilewith the correct base image and port exposure
- Streamlit Community Cloud: Push to GitHub, connect at
- Verify -- Confirm the deployment is live and report the URL.
Database Connections¶
Bad: hardcoded paths that crash in the cloud
Good: environment-aware, works locally and in Streamlit Cloud
import os
import duckdb
import streamlit as st
@st.cache_resource
def get_connection():
db_url = os.environ.get("DATABASE_URL", "local.duckdb")
return duckdb.connect(db_url, read_only=True)
On Streamlit Cloud, set DATABASE_URL in the app's Secrets management. Locally, it falls back to a local DuckDB file.
Caching¶
Streamlit reruns the entire script on every user interaction. Without caching, data reloads on every button click.
Bad: reloads data on every interaction
Good: cached with TTL for fresh data
Use @st.cache_data for DataFrames and serializable objects. Use @st.cache_resource for database connections and ML models.
Layout¶
Bad: everything in a single column with no structure
Good: organized with columns, tabs, and sidebar filters
st.set_page_config(layout="wide", page_title="Sales Dashboard")
with st.sidebar:
date_range = st.date_input("Date Range", value=(start, end))
region = st.selectbox("Region", ["All"] + regions)
col1, col2, col3 = st.columns(3)
col1.metric("Sales", f"${total:,.0f}", f"{delta:+.1f}%")
col2.metric("Orders", orders)
col3.metric("Avg Order", f"${avg:,.2f}")
tab1, tab2 = st.tabs(["Charts", "Data"])
with tab1:
st.plotly_chart(fig, use_container_width=True)
with tab2:
st.dataframe(df, use_container_width=True)
Secrets Management¶
| Environment | Method |
|---|---|
| Local dev | .env file loaded with python-dotenv or .streamlit/secrets.toml |
| Streamlit Cloud | App settings > Secrets (TOML format) |
| Docker | --env-file .env flag or Docker Compose env_file directive |
Streamlit secrets.toml format
Access in code withst.secrets["DATABASE_URL"].
Pre-Deployment Checklist¶
- All imports listed in
requirements.txtwith pinned versions - No absolute file paths -- use relative paths or environment variables
- Secrets in
.streamlit/secrets.tomlor env vars, never in source code st.set_page_config()called as the first Streamlit command- Heavy computations wrapped in
@st.cache_dataor@st.cache_resource .streamlit/config.tomlpresent for consistent theming
Notes¶
- Always set
layout="wide"for data-heavy dashboards with multiple charts or tables. - Add a
.streamlit/config.tomlfor theme consistency across local and deployed environments. - For Docker deployments, expose port 8501 and set
--server.address 0.0.0.0. - Streamlit Cloud provides free hosting for public repos. Private repos require a paid plan.
- The pre-push secret scan pairs with Secrets Audit for a deeper pass that includes git history.