Deploy a Flask app
Your Flask app on a computer of its own. Push to GitHub, run deploy.
Shelley handles the setup. About 10 minutes.
Prefer a terminal?
curl -fsSL https://exe.dev/deploy/flask/prompt.txt | ssh exe.dev new --prompt=/dev/stdinYour Flask app on a VM of its own, with a real disk: SQLite and uploads are still there tomorrow, nothing sleeps or cold-starts, and when something breaks there's a shell and an agent on the box. exe.dev keeps the app private until you share it and tells it who's visiting, so an internal tool needs no login code. LLM calls need no API key.
The setup is the one Flask's deployment docs describe: gunicorn behind nginx, with uv installing Python and your dependencies.
What you get#
- Your Flask app, or a new Flask 3.1 app with Flask-SQLAlchemy and Flask-Migrate, served by gunicorn behind nginx on port 8000, under systemd and enabled to start after a reboot.
deploy(in /usr/local/bin) pulls~/srcfrom its origin, builds the commit in a new~/releasesdirectory, runsflask db upgrade, switches~/appto it, restarts and checks it answers; any failure leaves the running release up.- Settings for exe.dev's proxy outside the repository, in
~/app.envand~/app-settings, with a generated secret key, ProxyFix for the forwarded headers, and gunicorn workers sized to the VM. - SQLite in WAL mode at
~/data/app.db(or the app's own database), with Flask's static folder served by nginx. - The owner's exe.dev email in
FLASK_ADMIN_EMAILS, and a new app that signs visitors in from theX-ExeDev-Emailheader. - Nightly backups in
~/backups, with a first one taken and checked.
What's running, and where
https://my-flask.exe.xyz/
your app, signed in with exe.dev, until you make it public
my-flask.exe.xyz:src
the code on the VM, if it isn't on GitHub
app.service: gthread workers sized to the VM, on a Unix socket
Deploy with Shelley#
Click Deploy and Shelley will set up Flask on a new VM, then check that it works. No config-file wrangling required.
Have these ready; Shelley asks for them:
REPO: the GitHub repository to deploy, as owner/name or a URL, ornewto start a fresh Flask app
Prefer a terminal?
curl -fsSL \
https://exe.dev/deploy/flask/prompt.txt \
| ssh exe.dev new --prompt=/dev/stdinWhen it's done, run this on your computer (only you can):
ssh my-flask.exe.xyz deploy # after each git push to GitHub
git clone my-flask.exe.xyz:src my-flask # if you started a new app and it isn't on GitHub yetWhat Shelley is told
REPO=<fill-this-in>
Set up Flask on this VM by following the exe.dev recipe at https://exe.dev/deploy/flask.md from top to bottom.
The values at the top of this message are mine:
- REPO: the GitHub repository to deploy, as owner/name or a URL, or `new` to start a fresh Flask app
Ask me for any that still say <fill-this-in> before you need them.
The recipe's example VM name is my-flask. This VM's name is the output of `hostname`: use it wherever the recipe writes my-flask. Skip the step that creates the VM; you are on it.
You are done when all of these are true. Check each one yourself:
- Your Flask app, or a new Flask 3.1 app with Flask-SQLAlchemy and Flask-Migrate, served by gunicorn behind nginx on port 8000, under systemd and enabled to start after a reboot.
- `deploy` (in /usr/local/bin) pulls `~/src` from its origin, builds the commit in a new `~/releases` directory, runs `flask db upgrade`, switches `~/app` to it, restarts and checks it answers; any failure leaves the running release up.
- Settings for exe.dev's proxy outside the repository, in `~/app.env` and `~/app-settings`, with a generated secret key, ProxyFix for the forwarded headers, and gunicorn workers sized to the VM.
- SQLite in WAL mode at `~/data/app.db` (or the app's own database), with Flask's static folder served by nginx.
- The owner's exe.dev email in `FLASK_ADMIN_EMAILS`, and a new app that signs visitors in from the `X-ExeDev-Email` header.
- Nightly backups in `~/backups`, with a first one taken and checked.
Read the whole recipe, including the closed details, and follow "Set it
up by hand" in order, skipping "Create the VM"; the walkthrough above it
is for the owner. REPO=new takes "Start a new app"; anything else takes
"Bring your repository". If cloning from GitHub fails, the repository is
private: give the owner the `ssh exe.dev integrations add github` command
from that step, with this VM's name and the repository, wait for them,
and clone from github.int.exe.xyz.
Never overwrite an existing ~/app.env. Don't commit to the owner's
repository or push to its origin. If their app doesn't fit (no factory
or `app` object Flask can find, settings read from other variable names,
a different database), set FLASK_APP and ~/app.env to fit it and tell
the owner what you changed and what their code should read.
Leave the VM private and don't reboot: check that app.service, nginx and
app-backup.timer are enabled instead. Skip the later Restore and Update
instructions; the restore check in setup uses a scratch copy only. Don't
turn on the optional timers, worker, or LLM endpoint unless asked.
Give the owner https://<vm>.exe.xyz/ and, of the two commands at the
end, the one that fits REPO.
Finish with the URLs I should open and these commands, which only I can run, from my own computer (with this VM's name in them):
ssh my-flask.exe.xyz deploy # after each git push to GitHub
git clone my-flask.exe.xyz:src my-flask # if you started a new app and it isn't on GitHub yet
Also at /deploy/flask/prompt.txt. The recipe it follows is /deploy/flask.md.
Open your app#
When Shelley finishes, open https://my-flask.exe.xyz/. A new app greets
you by your email address, with no password: exe.dev sends it with every
request, and a ten-line decorator reads it. Notes you
write are saved in SQLite at ~/data/app.db.
Deploy a change#
Push to GitHub, then tell the VM to deploy. On your computer:
git push origin main
ssh my-flask.exe.xyz deploy
It prints:
-----> Pulling main from origin
-----> Building 3f2a9c1
Installed 14 packages in 21ms
+ flask==3.1.3
...
-----> Checking myapp
-----> Migrating: 1c8e2a7d0b4f -> 9d1f3a2b7c55
-----> Starting 3f2a9c1
-----> Deployed 3f2a9c1: https://my-flask.exe.xyz/
Each commit is built beside the live release, checked, and migrated
(after a backup) before the app switches over. If any step fails, or the
new home page errors, the previous release keeps serving. To go back,
ssh my-flask.exe.xyz deploy 3f2a9c1. That restores code, not schema, so
add a column in one deploy and use it in the next.
Tip
To ship every push by itself, turn on deploy on push: the VM checks GitHub every minute. No webhook, no secrets in CI.
No GitHub?#
A new app's repository is ~/src on the VM. Clone it and push back to
it:
git clone my-flask.exe.xyz:src my-flask
cd my-flask
# change something, commit
git push
ssh my-flask.exe.xyz deploy
To move to GitHub later, connect an empty repository as in
Bring your repository and add it to ~/src as
origin; deploy then pulls from there.
Run it on your computer#
In your checkout:
uv run flask --app myapp db upgrade
FLASK_DEV_EMAIL=you@example.com uv run flask --app myapp run --debug
With no exe.dev proxy locally, debug mode takes your email from
FLASK_DEV_EMAIL.
What's different on the server#
Your repository doesn't change. gunicorn loads ~/app-settings/wsgi.py,
which finds your app the way flask --app does and wraps it in
ProxyFix:
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
So url_for(..., _external=True) builds https:// links and
request.remote_addr is the visitor, from exe.dev's X-Forwarded-*
headers.
- Settings and secrets:
~/app.env, wherefrom_prefixed_env()turnsFLASK_SECRET_KEYintoSECRET_KEY. Edit, thensudo systemctl restart app. - Logs:
journalctl -u app -f. - The Flask CLI with the server's settings:
app-flask shell,app-flask routes.
Who's signed in#
exe.dev lets in only you and the people you share the VM with, and adds
an X-ExeDev-Email header visitors can't fake
(Login with exe). myapp/auth.py reads it:
def current_email():
"""The signed-in visitor's email address, or None."""
email = request.headers.get("X-ExeDev-Email")
if not email and current_app.debug:
email = current_app.config.get("DEV_EMAIL") # flask run on your computer
return email.strip().lower() if email else None
def login_required(view):
@wraps(view)
def wrapped(*args, **kwargs):
g.email = current_email()
if g.email is None: # a public site, and they haven't signed in
return redirect("/__exe.dev/login?redirect=" + quote(request.full_path.rstrip("?")))
return view(*args, **kwargs)
return wrapped
Under @login_required, g.email is who's there; @admin_required also
checks FLASK_ADMIN_EMAILS in ~/app.env (yours, to start with). The
file works in any Flask app. To let a colleague in, on your computer:
ssh exe.dev share add my-flask colleague@example.com
ssh exe.dev share add my-flask team lets in your whole team.
The database#
The new app uses Flask-SQLAlchemy
with SQLite at ~/data/app.db, in WAL mode with a five-second busy
timeout, so reads never wait and writes queue instead of failing. For a schema change, edit a model and
make a Flask-Migrate migration on
your computer:
uv run flask --app myapp db migrate -m "add done to note"
Commit it with the model and deploy; deploy backs up and runs
flask db upgrade.
Use PostgreSQL instead#
Set up PostgreSQL on the VM with the
PostgreSQL page, and
uv add "psycopg[binary]" in your project. Then, on the VM, swap in its
DATABASE_URL and deploy, which creates the tables:
sed -i '/^DATABASE_URL=/d' ~/app.env && cat ~/postgres/myapp.env >> ~/app.env
deploy
Add After=postgresql.service under [Unit] in
/etc/systemd/system/app.service so the app starts after it at boot.
Static files and uploads#
nginx serves your static/ folder from disk, with nothing to configure.
Keep uploads in ~/data (say, FLASK_UPLOAD_FOLDER=/home/exedev/data/uploads
in ~/app.env), where deploys leave them and backups include them.
Your data#
Every night ~/backups gets the database, the rest of ~/data, the
settings, and the Git repository; it keeps a week. Copy them off the
VM too, from your computer:
scp -r my-flask.exe.xyz:backups my-flask-backups
They hold your secret key, so keep them private. Back up and restore has the rest.
Background jobs#
On a schedule: a
Flask CLI command
and a systemd timer. The new app's app-flask digest --send emails the
day's notes through exe.dev's email gateway; see
Run a job on a schedule.
After a request: for work it shouldn't wait for, queue a job with
RQ on Redis;
see Queue jobs with RQ. deploy restarts the
worker with the app.
Call an LLM#
From the VM, exe.dev's LLM gateway takes
OpenAI and Anthropic SDK calls with no API key, billed to your exe.dev
account. uv add openai, then stream an answer from a view:
from flask import Response, stream_with_context
from openai import OpenAI
llm = OpenAI(base_url="https://llm.int.exe.xyz/v1", api_key="unused")
@bp.post("/ask")
@login_required
def ask():
question = request.get_json()["question"]
def answer():
stream = llm.responses.create(model="gpt-6-luna", input=question, stream=True)
for event in stream:
if event.type == "response.output_text.delta":
yield event.delta
# X-Accel-Buffering: no tells nginx to pass each piece on at once.
return Response(stream_with_context(answer()), mimetype="text/plain",
headers={"X-Accel-Buffering": "no"})
Deploy, then try it on the VM:
curl -N localhost:8000/ask -H 'X-ExeDev-Email: you@example.com' \
-H 'Content-Type: application/json' -d '{"question": "Name three Flask extensions."}'
curl -s https://llm.int.exe.xyz/v1/models lists the models. Locally,
point base_url at a provider with your own key.
Keep API keys off the VM#
For other APIs, an HTTP proxy integration holds the key at exe.dev and adds it to each request. On your computer:
printf '%s' "$STRIPE_KEY" | ssh exe.dev integrations add http-proxy --name stripe \
--target https://api.stripe.com --bearer=- --attach vm:my-flask
The app calls https://stripe.int.exe.xyz/v1/..., and the key is never
on the VM (why that matters).
Share it, or make it public#
To open the app to everyone, on your computer:
ssh exe.dev share set-public my-flask
Pages under @login_required still send visitors to exe.dev's sign-in;
ssh exe.dev share set-private my-flask closes it again.
Use your own domain#
Point a CNAME at my-flask.exe.xyz (details), then on
your computer:
ssh exe.dev domain add my-flask app.example.com
exe.dev issues the certificate, and the app needs no change.
Workers and VM size#
gunicorn runs 2 × vCPUs + 1 workers of 4 threads each: 5 workers on
the default 2-vCPU VM, about 70 MB apiece for the new app. Override with
WEB_CONCURRENCY or GUNICORN_THREADS in ~/app.env. To grow the VM
(no reboot), on your computer:
ssh exe.dev resize my-flask --cpu=4 --memory=16GB
Then sudo systemctl restart app on the VM, and gunicorn starts 9.
Shelley is on call#
Shelley, the agent on your VM, is at https://my-flask.shelley.exe.xyz/.
Ask "why does /admin return 500?" or "add a CSV export of the notes": it
reads the logs, changes ~/src, pushes through the
GitHub integration, and deploys. For a
safer loop, give it a second VM to try changes on.
The nuts and bolts#
Happy with what Shelley set up? You can stop here. These are the same steps it followed, and the commands for later.
Set it up by hand
Create the VM#
On your computer (pick another name if my-flask is taken):
ssh exe.dev new --name=my-flask
ssh my-flask.exe.xyz
Everything else runs on the VM, as exedev.
Prepare the VM#
The layout: the Git checkout is ~/src, each deploy unpacks a commit into
~/releases/<time>-<commit>, and ~/app points at the live one. Data
lives in ~/data, settings in ~/app-settings and ~/app.env. nginx
(user www-data) serves static files from the releases, so it may pass
through your home directory without listing it; ~/data stays private.
chmod 711 ~
mkdir -p ~/releases ~/app-settings
install -d -m 700 ~/data
uv --version
uv comes with the VM. It installs the Python version your project asks
for (in .python-version or requires-python) on the first deploy.
Get your code#
Pick one. Both leave a Git checkout in ~/src.
Bring your repository
Set REPO to your repository and clone it. Public repositories clone
over HTTPS:
REPO=owner/name
slug=$(echo "$REPO" | sed -E 's#^(https://github\.com/|git@github\.com:)##; s#\.git$##; s#/$##')
git clone "https://github.com/$slug.git" ~/src
For a private repository, or to let Shelley push, connect it with the GitHub integration instead, so no token lands on the VM. On your computer:
ssh exe.dev integrations add github --name my-flask-repo --repository owner/name --attach vm:my-flask
Then clone through the integration, on the VM:
git clone "https://github.int.exe.xyz/$slug.git" ~/src
deploy expects either uv.lock, requirements.txt, or a
pyproject.toml with a [project] table at the top of the repository,
and ships the branch that's checked out. Check, and find your app:
cd ~/src && git branch --show-current
ls -A | grep -xE 'uv.lock|requirements.txt|pyproject.toml|.python-version|runtime.txt|.flaskenv|wsgi.py|app.py|migrations'
grep -rlE --include='*.py' 'def create_app|= *Flask\(' . | grep -v -e '/\.venv/' -e '/tests\?/' | head
Note the app's import path for FLASK_APP below: what you'd pass to
flask --app (app, wsgi, or a package with a create_app factory,
like myapp). If the repository has a .flaskenv with FLASK_APP, use
that. Your app gets a fresh database; to bring data, copy it in after the
first deploy.
A project that doesn't name its Python version (in .python-version,
requires-python, or runtime.txt) gets the newest one on the VM. If an
old pinned dependency won't install on it, add UV_PYTHON=3.12 to
~/app.env once it exists; deploy passes it to uv.
Start a new app
A small notes app: Flask with Flask-SQLAlchemy and Flask-Migrate, signed in by exe.dev. Create the project with uv:
mkdir ~/src && cd ~/src
git init --quiet -b main
uv init --quiet --no-package --python 3.14 --name myapp
rm main.py
uv add --quiet 'flask~=3.1.3' 'flask-sqlalchemy~=3.1.1' 'flask-migrate~=4.1.0' gunicorn
mkdir -p myapp/templates myapp/static
printf '%s\n' instance/ '*.db' >> .gitignore
The app factory, myapp/__init__.py. Settings come from the environment,
which on the VM is ~/app.env:
cat > myapp/__init__.py <<'EOF'
"""Notes: a small Flask app, signed in with exe.dev."""
import os
from flask import Flask, abort, request
from .models import db, migrate
def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = "dev" # on the VM, FLASK_SECRET_KEY replaces it
app.config["ADMIN_EMAILS"] = ""
url = os.environ.get("DATABASE_URL", "sqlite:///app.db") # in instance/
if url.startswith(("postgres://", "postgresql://")):
url = "postgresql+psycopg://" + url.split("://", 1)[1] # psycopg 3
app.config["SQLALCHEMY_DATABASE_URI"] = url
# FLASK_SECRET_KEY becomes SECRET_KEY, FLASK_ADMIN_EMAILS ADMIN_EMAILS...
app.config.from_prefixed_env()
db.init_app(app)
migrate.init_app(app, db)
@app.before_request
def refuse_cross_site_posts():
# Browsers say where a form post came from. exe.dev's login is a
# cookie, so refuse posts from other sites (CSRF).
if request.method not in ("GET", "HEAD", "OPTIONS"):
if request.headers.get("Sec-Fetch-Site") == "cross-site":
abort(403)
from . import commands, views
app.register_blueprint(views.bp)
app.cli.add_command(commands.digest)
return app
EOF
The database, myapp/models.py:
cat > myapp/models.py <<'EOF'
"""The database: Flask-SQLAlchemy models, migrated by Flask-Migrate."""
import sqlite3
from datetime import datetime, timezone
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
db = SQLAlchemy(model_class=Base)
# SQLite can't alter most of a table in place; batch mode copies it.
migrate = Migrate(render_as_batch=True)
@event.listens_for(Engine, "connect")
def tune_sqlite(conn, _record):
if isinstance(conn, sqlite3.Connection):
conn.execute("PRAGMA journal_mode=WAL") # readers don't wait for the writer
conn.execute("PRAGMA synchronous=NORMAL") # safe with WAL, and faster
conn.execute("PRAGMA busy_timeout=5000") # writers queue for up to 5 s
conn.execute("PRAGMA foreign_keys=ON")
class Note(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
author: Mapped[str]
text: Mapped[str]
created: Mapped[datetime] = mapped_column(default=lambda: datetime.now(timezone.utc))
EOF
Sign-in, myapp/auth.py, as in Who's signed in:
cat > myapp/auth.py <<'EOF'
"""Who's there? exe.dev's proxy says, in X-ExeDev-Email.
https://exe.dev/docs/login-with-exe
"""
from functools import wraps
from urllib.parse import quote
from flask import abort, current_app, g, redirect, request
def current_email():
"""The signed-in visitor's email address, or None."""
email = request.headers.get("X-ExeDev-Email")
if not email and current_app.debug:
email = current_app.config.get("DEV_EMAIL") # flask run on your computer
return email.strip().lower() if email else None
def login_required(view):
@wraps(view)
def wrapped(*args, **kwargs):
g.email = current_email()
if g.email is None: # a public site, and they haven't signed in
return redirect("/__exe.dev/login?redirect=" + quote(request.full_path.rstrip("?")))
return view(*args, **kwargs)
return wrapped
def admin_required(view):
@wraps(view)
@login_required
def wrapped(*args, **kwargs):
if g.email not in current_app.config["ADMIN_EMAILS"].lower().split(","):
abort(403)
return view(*args, **kwargs)
return wrapped
EOF
The pages, myapp/views.py:
cat > myapp/views.py <<'EOF'
from flask import Blueprint, g, redirect, render_template, request, url_for
from .auth import admin_required, login_required
from .models import Note, db
bp = Blueprint("notes", __name__)
@bp.get("/")
@login_required
def index():
notes = db.session.scalars(db.select(Note).order_by(Note.id.desc()).limit(50))
return render_template("index.html", notes=notes)
@bp.post("/")
@login_required
def add():
text = request.form.get("text", "").strip()
if text:
db.session.add(Note(author=g.email, text=text))
db.session.commit()
return redirect(url_for("notes.index"))
@bp.get("/admin")
@admin_required
def admin():
count = db.session.scalar(db.select(db.func.count(Note.id)))
return {"admin": g.email, "notes": count, "url": url_for("notes.index", _external=True)}
EOF
The nightly job, myapp/commands.py, a Flask CLI command:
cat > myapp/commands.py <<'EOF'
"""flask digest: the last day's notes, printed or emailed."""
import json
import urllib.request
from datetime import datetime, timedelta, timezone
import click
from flask import current_app
from .models import Note, db
# exe.dev's email gateway: https://exe.dev/docs/send-email
GATEWAY = "http://169.254.169.254/gateway/email/send"
@click.command()
@click.option("--send", is_flag=True, help="Email it to ADMIN_EMAILS.")
def digest(send):
"""Sum up the notes from the last 24 hours."""
since = datetime.now(timezone.utc) - timedelta(days=1)
notes = db.session.scalars(db.select(Note).where(Note.created >= since)).all()
subject = f"{len(notes)} new notes"
body = "\n".join(f"- {n.author}: {n.text}" for n in notes) or "Nothing new."
if not send:
click.echo(f"{subject}\n{body}")
return
for to in filter(None, current_app.config["ADMIN_EMAILS"].split(",")):
data = json.dumps({"to": to, "subject": subject, "body": body}).encode()
req = urllib.request.Request(GATEWAY, data, {"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=10).close()
click.echo(f"Sent to {to}")
EOF
The page and its stylesheet:
cat > myapp/templates/index.html <<'EOF'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Notes</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Hello from Flask</h1>
<p>You're signed in as <strong>{{ g.email }}</strong>, by exe.dev.</p>
<form method="post">
<input name="text" placeholder="Write a note" autofocus required>
<button>Save</button>
</form>
<ul>
{% for note in notes %}
<li>{{ note.text }} <small>{{ note.author }}</small></li>
{% endfor %}
</ul>
<p><small>Edit <code>myapp/templates/index.html</code>, commit, and run
<code>deploy</code>.</small></p>
</body>
</html>
EOF
cat > myapp/static/style.css <<'EOF'
body { font: 18px/1.5 system-ui, sans-serif; max-width: 36rem; margin: 4rem auto; padding: 0 1rem; }
input { font: inherit; width: 70%; }
button { font: inherit; }
small { color: #666; }
EOF
Create the first migration from the model, check the app, and commit as the VM's owner:
cd ~/src
uv run flask --app myapp db init
uv run flask --app myapp db migrate -m "Create notes"
uv run flask --app myapp routes
rm -rf instance
cat > README.md <<'EOF'
# myapp
Run it locally:
uv run flask --app myapp db upgrade
FLASK_DEV_EMAIL=you@example.com uv run flask --app myapp run --debug
Deploy: commit, push, and run `deploy` on the VM.
EOF
email=$(curl -fsS https://reflection.int.exe.xyz/email | jq -r .email)
git add .gitignore .python-version README.md pyproject.toml uv.lock myapp migrations
git -c user.name="$email" -c user.email="$email" commit --quiet -m "New Flask app"
git log --oneline
The routes list shows notes.index, notes.add, notes.admin, and
static.
Settings#
~/app.env holds the secrets and per-server values; systemd, deploy
and app-flask all read it, so keep to KEY=value lines, without quotes
or spaces. FLASK_APP is your app's import path (myapp for a new app).
This writes the file once, with a new secret key:
FLASK_APP=myapp # yours, from "Bring your repository"
if [ ! -e ~/app.env ]; then
install -m 600 /dev/null ~/app.env
cat >> ~/app.env <<EOF
# The Flask app's settings on this VM, read by app.service, deploy and
# app-flask. One KEY=value per line: no quotes, no spaces.
FLASK_APP=$FLASK_APP
FLASK_SECRET_KEY=$(openssl rand -hex 32)
FLASK_ADMIN_EMAILS=$(curl -fsS https://reflection.int.exe.xyz/email | jq -r .email)
DATABASE_URL=sqlite:////home/exedev/data/app.db
DEPLOY_BRANCH=$(git -C ~/src branch --show-current)
EOF
fi
grep -v SECRET ~/app.env
If your app reads its settings from other names (SECRET_KEY,
SQLALCHEMY_DATABASE_URI), add lines with those names too.
The WSGI entry point gunicorn loads. It finds the app as flask --app
does and adds ProxyFix:
cat > ~/app-settings/wsgi.py <<'EOF'
"""The app gunicorn serves: FLASK_APP from ~/app.env, behind ProxyFix.
exe.dev's proxy and nginx pass the visitor's scheme, host and address in
X-Forwarded-Proto, -Host and -For; trust one hop of each.
"""
import os
from flask.cli import ScriptInfo
from werkzeug.middleware.proxy_fix import ProxyFix
# Find the app the way `flask --app $FLASK_APP` does.
app = ScriptInfo(app_import_path=os.environ["FLASK_APP"]).load_app()
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
EOF
gunicorn's settings. The worker count follows the VM's size unless
~/app.env says otherwise:
cat > ~/app-settings/gunicorn.conf.py <<'EOF'
"""gunicorn settings: https://gunicorn.org/reference/settings/"""
import os
wsgi_app = "wsgi:app"
pythonpath = "/home/exedev/app-settings"
# nginx connects here; RuntimeDirectory= in app.service creates /run/app.
bind = "unix:/run/app/gunicorn.sock"
# Processes: 2 per vCPU, plus one. Each has a pool of threads, so a slow
# API or LLM call holds one thread, not a whole worker.
workers = int(os.environ.get("WEB_CONCURRENCY") or 2 * os.cpu_count() + 1)
worker_class = "gthread"
threads = int(os.environ.get("GUNICORN_THREADS") or 4)
# Replace each worker after about 1,000 requests, against slow leaks.
max_requests = 1000
max_requests_jitter = 100
accesslog = "-" # to the journal: journalctl -u app
# The visitor's address and exe.dev email, from the proxy's headers.
access_log_format = '%({x-forwarded-for}i)s %({x-exedev-email}i)s %(t)s "%(r)s" %(s)s %(b)s %(M)sms'
EOF
The deploy command#
deploy pulls ~/src from its origin, if it has one, builds the
branch's newest commit (or the one you name) in a new release, checks the
app loads, links its static folder for nginx, backs up and migrates the
database if a migration is waiting, then points ~/app at the release,
restarts, and asks for the home page as you (as exe.dev's proxy would),
expecting anything but a server error. If any step fails, the release is
thrown away and the running one stays (or is put back).
sudo tee /usr/local/bin/deploy >/dev/null <<'EOF'
#!/usr/bin/env bash
# deploy [commit]: pull ~/src from its origin and ship DEPLOY_BRANCH, or
# ship the commit you name. Builds a release in ~/releases, migrates,
# switches ~/app to it, restarts, and checks it answers. A failure leaves
# (or puts back) the running release.
# deploy --if-changed: only if the branch moved since the last deploy.
set -euo pipefail
umask 022
[ "$(id -un)" = exedev ] || exec sudo -u exedev -i "$0" "$@"
exec 9>"$HOME/.deploy.lock" && flock 9
set -a; . "$HOME/app.env"; set +a
branch=${DEPLOY_BRANCH:-main}
cd "$HOME/src"
want=; if_changed=
for arg in "$@"; do
case "$arg" in --if-changed) if_changed=1 ;; *) want=$arg ;; esac
done
if [ -z "$want" ]; then
if git remote get-url origin >/dev/null 2>&1; then
[ -n "$if_changed" ] || echo "-----> Pulling $branch from origin"
git switch --quiet "$branch"
git pull --quiet --ff-only origin "$branch"
fi
want=$branch
fi
sha=$(git rev-parse --verify "$want^{commit}")
if [ -n "$if_changed" ]; then
[ "$sha" != "$(cat "$HOME/.deployed" 2>/dev/null)" ] || exit 0
fi
echo "$sha" > "$HOME/.deployed"
rel="$HOME/releases/$(date -u +%Y%m%d-%H%M%S)-${sha:0:7}"
prev=$(readlink "$HOME/app" || true)
# Remove the new release unless it ended up live.
trap '[ "$(readlink -f "$HOME/app")" = "$rel" ] || rm -rf "$rel"' EXIT
echo "-----> Building ${sha:0:7}"
mkdir -p "$rel"
git archive "$sha" | tar -x -C "$rel"
echo "$sha" > "$rel/REVISION"
cd "$rel"
if [ -f uv.lock ]; then
uv sync --locked --no-dev
elif [ -f requirements.txt ]; then
py=
if [ ! -f .python-version ] && [ -f runtime.txt ]; then
# Heroku's runtime.txt: python-3.12.4 means Python 3.12.
py=$(sed -n 's/^python-\([0-9]*\.[0-9]*\).*/\1/p' runtime.txt)
fi
uv venv --quiet ${py:+--python "$py"}
uv pip install -r requirements.txt
else
uv sync --no-dev
fi
uv pip install --quiet gunicorn # does nothing if the project has it
echo "-----> Checking $FLASK_APP"
# Load the app as gunicorn will, so a broken import stops here, and link
# its static folder where nginx looks: ~/app/.nginx/static.
.venv/bin/python - <<'PY'
import os, sys
sys.path.insert(0, os.path.expanduser("~/app-settings"))
from wsgi import app
os.mkdir(".nginx")
if app.has_static_folder and app.static_url_path == "/static":
os.symlink(app.static_folder, ".nginx/static")
PY
if [ -d migrations ] && .venv/bin/python -c 'import flask_migrate' 2>/dev/null; then
heads=$(.venv/bin/flask db heads 2>/dev/null | awk '{print $1}' | sort | xargs)
if ! current=$(.venv/bin/flask db current 2>/dev/null | awk '{print $1}' | sort | xargs); then
# An older commit: the database has migrations this release lacks.
echo "-----> Not migrating: the database is newer than ${sha:0:7}'s migrations"
elif [ "$current" != "$heads" ]; then
echo "-----> Migrating: ${current:-empty} -> $heads"
/usr/local/bin/app-backup >/dev/null
.venv/bin/flask db upgrade
fi
fi
switch() { ln -sfn "$1" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app"; }
restart() {
sudo systemctl restart app
if systemctl is-enabled --quiet app-worker 2>/dev/null; then sudo systemctl restart app-worker; fi
}
echo "-----> Starting ${sha:0:7}"
switch "$rel"
restart
# Ask for the home page as the first admin, the way exe.dev's proxy would.
as_owner=(-H "X-ExeDev-Email: ${FLASK_ADMIN_EMAILS%%,*}" -H 'X-Forwarded-Proto: https')
for _ in $(seq 30); do
code=$(curl -s -o /dev/null -w '%{http_code}' "${as_owner[@]}" http://localhost:8000/ || true)
case "$code" in [1234]??|500) break ;; esac
# Stop waiting once gunicorn has crashed and systemd restarted it.
[ "$(systemctl show app -p NRestarts --value)" = 0 ] || break
sleep 1
done
case "$code" in
[1234]??) ;;
*)
echo "-----> The new release answered HTTP $code. Logs:"
journalctl -u app -n 40 -o cat --no-pager || true
if [ -n "$prev" ]; then echo "-----> Going back to $prev"; switch "$prev"; restart; fi
exit 1 ;;
esac
# Keep the five newest releases.
ls -1d "$HOME"/releases/*/ | sort | head -n -5 | xargs -r rm -rf
echo "-----> Deployed ${sha:0:7}: https://$(hostname).exe.xyz/"
EOF
sudo chmod 755 /usr/local/bin/deploy
app-flask runs the Flask CLI in the live release with the server's
settings:
sudo tee /usr/local/bin/app-flask >/dev/null <<'EOF'
#!/bin/sh
# app-flask <command>: the flask CLI for the live app, with its settings.
set -a; . "$HOME/app.env"; set +a
cd "$HOME/app" && exec .venv/bin/flask "$@"
EOF
sudo chmod 755 /usr/local/bin/app-flask
Let git push from your computer update ~/src when it has no GitHub
remote (No GitHub?). The push is refused if someone has
uncommitted changes there:
git -C ~/src config receive.denyCurrentBranch updateInstead
Back up nightly#
app-backup takes a consistent copy of the SQLite database with its
backup command (copying a live database file with cp can catch it
half-written), checks it, and packs it with the rest of ~/data,
~/app.env, ~/app-settings, and a bundle of the Git repository. It
keeps seven.
sudo tee /usr/local/bin/app-backup >/dev/null <<'EOF'
#!/usr/bin/env bash
# Back up the Flask app to ~/backups: the SQLite database, the rest of
# ~/data, the settings and secrets, and ~/src's Git repository. Keeps 7.
set -euo pipefail
umask 077
cd "$HOME"
mkdir -p backups
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
if [ -f data/app.db ]; then
sqlite3 data/app.db ".backup '$work/app.db'"
test "$(sqlite3 "$work/app.db" 'PRAGMA integrity_check')" = ok
fi
git -C src bundle create --quiet "$work/src.bundle" --all
out="$HOME/backups/app-$(date -u +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$out.part" --exclude=__pycache__ \
--exclude='data/app.db' --exclude='data/app.db-*' \
-C "$work" . -C "$HOME" app.env app-settings data
mv "$out.part" "$out"
ls -1 backups/app-*.tar.gz | sort | head -n -7 | xargs -r rm --
echo "$out"
EOF
sudo chmod 755 /usr/local/bin/app-backup
A timer runs it every night:
sudo tee /etc/systemd/system/app-backup.service >/dev/null <<'EOF'
[Unit]
Description=Back up the Flask app to ~/backups
[Service]
Type=oneshot
User=exedev
ExecStart=/usr/local/bin/app-backup
EOF
sudo tee /etc/systemd/system/app-backup.timer >/dev/null <<'EOF'
[Unit]
Description=Back up the Flask app nightly
[Timer]
OnCalendar=*-*-* 03:00:00
RandomizedDelaySec=30m
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now app-backup.timer
Run it with systemd and nginx#
app.service runs gunicorn from whichever release ~/app points at, and
restarts it if it stops:
sudo tee /etc/systemd/system/app.service >/dev/null <<'EOF'
[Unit]
Description=Flask app (gunicorn)
After=network.target
[Service]
User=exedev
Group=exedev
WorkingDirectory=/home/exedev/app
EnvironmentFile=/home/exedev/app.env
Environment=PYTHONUNBUFFERED=1
RuntimeDirectory=app
ExecStart=/home/exedev/app/.venv/bin/gunicorn --config /home/exedev/app-settings/gunicorn.conf.py
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable app
nginx listens on port 8000, where exe.dev's HTTPS proxy sends traffic. It answers from the release's static folder when the file exists and passes everything else to gunicorn, along with exe.dev's headers. It replaces nginx's default site, which also uses port 8000.
sudo tee /etc/nginx/sites-available/app >/dev/null <<'EOF'
# exe.dev's proxy -> nginx :8000 -> gunicorn on /run/app/gunicorn.sock.
server {
listen 8000 default_server;
listen [::]:8000 default_server;
server_name _;
client_max_body_size 100m;
gzip_types text/css application/javascript application/json image/svg+xml;
# Only static/ is in here: deploy links Flask's static folder to it.
root /home/exedev/app/.nginx;
location / {
try_files $uri @flask;
}
location @flask {
proxy_pass http://unix:/run/app/gunicorn.sock;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header X-Forwarded-Host $http_x_forwarded_host;
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_redirect off;
proxy_read_timeout 300s;
}
}
EOF
sudo rm -f /etc/nginx/sites-enabled/default
sudo ln -sf /etc/nginx/sites-available/app /etc/nginx/sites-enabled/app
sudo nginx -t
sudo systemctl enable --now nginx
sudo systemctl reload nginx
Expect syntax is ok and test is successful. Until the first deploy,
curl localhost:8000 returns 502: gunicorn isn't running yet.
Deploy#
The first deploy also downloads Python if needed:
deploy
It ends with -----> Deployed. Then switch the SQLite database to WAL
mode, which sticks to the file, in case your app doesn't. Check the app as exe.dev's proxy would
call it, with your address in the header and HTTPS forwarded; a static
file from nginx; and the app and Python versions:
email=$(curl -fsS https://reflection.int.exe.xyz/email | jq -r .email)
proxy=(-H "X-ExeDev-Email: $email" -H 'X-Forwarded-Proto: https' -H "X-Forwarded-Host: $(hostname).exe.xyz")
curl -s -o /dev/null -w '%{http_code}\n' "${proxy[@]}" http://localhost:8000/
curl -s "${proxy[@]}" http://localhost:8000/admin; echo
curl -sI http://localhost:8000/static/style.css | grep -iE '^(HTTP|server|content-type)'
app-flask --version
[ ! -f ~/data/app.db ] || sqlite3 ~/data/app.db 'PRAGMA journal_mode=WAL'
systemctl is-enabled app nginx app-backup.timer
For a new app, expect 200; JSON with your address as admin and an
https:// URL; 200 from nginx for the stylesheet; Flask 3.1.3 on
Python 3.14; wal; and enabled three times. Your own app may answer
its home page with a redirect, or a 404 if it has none; /admin and
the stylesheet are the new app's.
Test a backup#
Take one now and check it in a scratch directory: the database passes an integrity check, and the repository bundle has your commit.
backup=$(app-backup)
rm -rf /tmp/restore-check && mkdir /tmp/restore-check
tar -xzf "$backup" -C /tmp/restore-check
ls /tmp/restore-check
[ ! -f /tmp/restore-check/app.db ] || sqlite3 /tmp/restore-check/app.db 'PRAGMA integrity_check; SELECT version_num FROM alembic_version;'
git -C /tmp/restore-check bundle list-heads src.bundle
rm -rf /tmp/restore-check
Expect app-settings app.db app.env data src.bundle, ok, the
migration's revision, and your branch. Setup is done: everything is
enabled to start at boot. Continue with Open your app.
Deploy on push
To deploy every new commit on the branch without running deploy, run
deploy --if-changed every minute. It pulls from GitHub and does nothing
unless the branch moved since the last deploy; a commit that fails to
deploy isn't tried again until the next one arrives. On the VM:
sudo tee /etc/systemd/system/app-autodeploy.service >/dev/null <<'EOF'
[Unit]
Description=Deploy the Flask app if its branch moved
[Service]
Type=oneshot
User=exedev
ExecStart=/usr/local/bin/deploy --if-changed
EOF
sudo tee /etc/systemd/system/app-autodeploy.timer >/dev/null <<'EOF'
[Unit]
Description=Check for new commits every minute
[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now app-autodeploy.timer
Deploys show up in journalctl -u app-autodeploy. To roll back while it's
on, revert the commit and push, or sudo systemctl stop app-autodeploy.timer first and deploy <commit>.
Run a job on a schedule
A systemd timer runs app-flask digest --send at 07:00 UTC every day.
Try the command first, then create the timer. On the VM:
app-flask digest
sudo tee /etc/systemd/system/app-digest.service >/dev/null <<'EOF'
[Unit]
Description=Email the day's notes
[Service]
Type=oneshot
User=exedev
ExecStart=/usr/local/bin/app-flask digest --send
EOF
sudo tee /etc/systemd/system/app-digest.timer >/dev/null <<'EOF'
[Unit]
Description=Email the day's notes every morning
[Timer]
OnCalendar=*-*-* 07:00:00 UTC
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now app-digest.timer
systemctl list-timers app-digest.timer
Persistent=true runs a missed job after a restart. Its output is in
journalctl -u app-digest.
Queue jobs with RQ
Set up Redis with the Redis page,
which adds a REDIS_URL line to ~/app.env. Then add RQ to your project, on your
computer:
uv add rq
The job is a plain function, myapp/tasks.py:
"""Jobs for the RQ worker, app-worker.service."""
from . import create_app
from .models import Note, db
app = create_app()
def count_words(note_id):
with app.app_context():
note = db.session.get(Note, note_id)
app.logger.warning("note %s has %s words", note_id, len(note.text.split()))
In a view, queue it by name and return at once:
import os
from redis import Redis
from rq import Queue
queue = Queue(connection=Redis.from_url(os.environ["REDIS_URL"]))
# after db.session.commit():
queue.enqueue("myapp.tasks.count_words", note.id)
On the VM, create the worker's service before you deploy. deploy
restarts it along with the app, so it always runs the live code:
sudo tee /etc/systemd/system/app-worker.service >/dev/null <<'EOF'
[Unit]
Description=RQ worker for the Flask app
After=network.target redis-server.service
[Service]
User=exedev
WorkingDirectory=/home/exedev/app
EnvironmentFile=/home/exedev/app.env
ExecStart=/home/exedev/app/.venv/bin/rq worker --url ${REDIS_URL} default
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable app-worker
Commit, push, and deploy. journalctl -u app-worker -f shows each job.
Back up and restore
Take a backup any time, on the VM: app-backup. It prints the archive's
path. Copy archives off the VM as in Your data.
Restore on the same VM#
Use your archive's name. This stops the app, keeps a copy of the current
database in ~/data/app.before-restore.db, restores the database and the
rest of ~/data, and starts the app again:
backup=~/backups/app-20261116-030000.tar.gz
rm -rf /tmp/restore && mkdir /tmp/restore && tar -xzf "$backup" -C /tmp/restore
sudo systemctl stop app
sqlite3 ~/data/app.db ".backup '$HOME/data/app.before-restore.db'"
sqlite3 ~/data/app.db ".restore '/tmp/restore/app.db'"
rsync -a --exclude='app.db*' --exclude=app.before-restore.db /tmp/restore/data/ ~/data/
sudo systemctl start app
rm -rf /tmp/restore
If you run app-worker, stop and start it with app. The code doesn't
change; to go back to an older release too, deploy <commit>.
Restore on a new VM#
Create a VM and copy the archive to it. On your computer:
ssh exe.dev new --name=my-flask-2
scp app-20261116-030000.tar.gz my-flask-2.exe.xyz:
On the new VM, put the settings, data and repository in place:
mkdir /tmp/restore && tar -xzf ~/app-20261116-030000.tar.gz -C /tmp/restore
chmod 711 ~
mkdir -p ~/releases
cp -a /tmp/restore/app.env /tmp/restore/app-settings /tmp/restore/data ~/
install -m 600 /tmp/restore/app.db ~/data/app.db
git clone --quiet /tmp/restore/src.bundle ~/src
If ~/src came from GitHub, point it back there:
git -C ~/src remote set-url origin https://github.com/owner/name.git.
Then follow Set it up by hand from The deploy
command to the end; its Deploy step starts the app. Set up any
worker or timers again as in Background jobs. For a
copy of the whole VM instead, run ssh exe.dev cp my-flask my-flask-2 on
your computer.
Update Flask, Python, and uv
Flask and your other dependencies are pinned in your project's
uv.lock, so updates are commits. In your project, on your computer:
uv lock --upgrade
uv run flask --app myapp routes
git commit -am "Update dependencies" && git push
Then deploy. The ~=3.1.3 pin in a new app takes 3.1.x releases; for
the next feature release, read Flask's
changes and
change the pin. Python follows .python-version: change it, run
uv lock, commit, push, and deploy; uv installs the new version on the
VM during the deploy.
uv itself is in /usr/local/bin. To update it, on the VM:
curl -LsSf https://astral.sh/uv/install.sh | sudo env UV_UNMANAGED_INSTALL=/usr/local/bin sh
uv --version
nginx and the rest of Ubuntu update with sudo apt update && sudo apt upgrade.
Something not working?
On the VM, start with the logs:
journalctl -u app -n 50 --no-pager
sudo tail -n 20 /var/log/nginx/error.log
ls -l ~/app
- 502 Bad Gateway: gunicorn isn't running, or is still starting.
journalctl -u appshows why: usually an import error, or a setting missing from~/app.env. Could not locate a Flask applicationduring a deploy:FLASK_APPin~/app.envdoesn't match your code. It takes whatflask --appdoes: a module (app), a package withcreate_app(myapp), ormodule:name.deploystops at "Pulling":~/srchas local changes or commits GitHub doesn't.git -C ~/src statusshows which; commit and push them, orgit -C ~/src reset --hard origin/mainto drop them.- Links and redirects say
http://: the app isn't behind ProxyFix. Checkapp.servicestarts gunicorn with~/app-settings/gunicorn.conf.py, which loadswsgi.py. - No
X-ExeDev-Emailon a public site: visitors who haven't signed in don't send it. Send them to/__exe.dev/login?redirect=/, as@login_requireddoes. - 403 on a form post: the starter refuses posts from other sites. A form on your own pages is fine; for an API called from another site, drop the check and protect it another way.
- "database is locked": a write transaction held the lock for more than 5 seconds. Keep transactions short and move slow work to a background job.
- Static files are 404:
ls -l ~/app/.nginxshould showstaticlinked to your app's static folder. An app whose static URL isn't/staticis served by Flask instead. - 413 Request Entity Too Large: raise
client_max_body_sizein/etc/nginx/sites-available/app, thensudo systemctl reload nginx. - A worker was killed with
WORKER TIMEOUT: a request took more than 30 seconds without its thread letting go. Raisetimeoutingunicorn.conf.py, or move the work to RQ.
Frequently asked questions#
How many gunicorn workers should I run?
Two per vCPU plus one, gunicorn's rule of thumb: 5 on a default 2-vCPU VM, each with 4 threads so a slow API call holds a thread, not a process. Set WEB_CONCURRENCY in ~/app.env to override it.
Is SQLite enough for a production Flask app?
For most apps on one server, yes: in WAL mode it handles thousands of page views a minute. Move to PostgreSQL when several servers share the data or long transactions write a lot; it's one line in ~/app.env.
Why not `flask run` in production?
Flask's own docs say the development server isn't built for security, speed, or many visitors. gunicorn runs several workers and replaces one that crashes; systemd restarts gunicorn.
Do I need ProxyFix?
Yes. Without it Flask sees plain HTTP from 127.0.0.1, so external URLs say http:// and request.remote_addr is never the visitor. ~/app-settings/wsgi.py adds it, so your code doesn't change.
Can I use Docker instead?
Yes, Docker comes with the VM; see Docker Compose. Running the app directly keeps deploys fast and the logs and database one ssh away.
What does it cost?
Flask is free (BSD). You pay for the VM, not per request (pricing), and one VM can run several small apps.
Updated Nov 16, 2026 · tested end to end Nov 16, 2026 · Markdown · manifest.json · Something wrong? Tell us