---
title: "Deploy a Flask app"
description: "Deploy Flask to a VM of its own: gunicorn under systemd, SQLite or PostgreSQL on a persistent disk, git pull deploys, and sign-in by exe.dev."
url: https://exe-staging.dev/deploy/flask
category: "Frameworks"
updated: 2026-11-16
---

# Deploy a Flask app

Your Flask app on a computer of its own. Push to GitHub, run deploy.

- **Software:** Flask (https://flask.palletsprojects.com)
- **Source:** https://github.com/pallets/flask
- **License:** BSD-3-Clause
- **Time:** 10 minutes
- **Example VM name:** `my-flask` (yours will differ; on the VM, `hostname` prints it)
- **Machine-readable:** https://exe-staging.dev/deploy/flask/manifest.json

## 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 `~/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.

Running on the VM:

- **Your Flask app**: Flask 3.1 on Python 3.14, installed by uv; one release per deploy, data in `~/app`
- **gunicorn**: `app.service`: gthread workers sized to the VM, on a Unix socket
- **nginx**: static files, and a buffer in front of gunicorn, port 8000
- **SQLite**: Flask-SQLAlchemy and Flask-Migrate, WAL mode, data in `~/data/app.db`
- **deploy**: pulls from GitHub, builds, migrates, restarts, rolls back on failure, data in `~/src`
- **Nightly backups**: database, data, settings, and code; keeps a week, data in `~/backups`

How it is reached:

- https://my-flask.exe.xyz/ (private): your app, signed in with exe.dev, until you make it public
- my-flask.exe.xyz:src (private): the code on the VM, if it isn't on GitHub

## Deploy with Shelley

Open https://exe-staging.dev/new?prompt=REPO%3D%3Cfill-this-in%3E%0A%0ASet%20up%20Flask%20on%20this%20VM%20by%20following%20the%20exe.dev%20recipe%20at%20https%3A%2F%2Fexe-staging.dev%2Fdeploy%2Fflask.md%20from%20top%20to%20bottom.%0A%0AThe%20values%20at%20the%20top%20of%20this%20message%20are%20mine%3A%0A-%20REPO%3A%20the%20GitHub%20repository%20to%20deploy%2C%20as%20owner%2Fname%20or%20a%20URL%2C%20or%20%60new%60%20to%20start%20a%20fresh%20Flask%20app%0AAsk%20me%20for%20any%20that%20still%20say%20%3Cfill-this-in%3E%20before%20you%20need%20them.%0A%0AThe%20recipe%27s%20example%20VM%20name%20is%20my-flask.%20This%20VM%27s%20name%20is%20the%20output%20of%20%60hostname%60%3A%20use%20it%20wherever%20the%20recipe%20writes%20my-flask.%20Skip%20the%20step%20that%20creates%20the%20VM%3B%20you%20are%20on%20it.%0A%0AYou%20are%20done%20when%20all%20of%20these%20are%20true.%20Check%20each%20one%20yourself%3A%0A-%20Your%20Flask%20app%2C%20or%20a%20new%20Flask%203.1%20app%20with%20Flask-SQLAlchemy%20and%20Flask-Migrate%2C%20served%20by%20gunicorn%20behind%20nginx%20on%20port%208000%2C%20under%20systemd%20and%20enabled%20to%20start%20after%20a%20reboot.%0A-%20%60deploy%60%20%28in%20%2Fusr%2Flocal%2Fbin%29%20pulls%20%60~%2Fsrc%60%20from%20its%20origin%2C%20builds%20the%20commit%20in%20a%20new%20%60~%2Freleases%60%20directory%2C%20runs%20%60flask%20db%20upgrade%60%2C%20switches%20%60~%2Fapp%60%20to%20it%2C%20restarts%20and%20checks%20it%20answers%3B%20any%20failure%20leaves%20the%20running%20release%20up.%0A-%20Settings%20for%20exe.dev%27s%20proxy%20outside%20the%20repository%2C%20in%20%60~%2Fapp.env%60%20and%20%60~%2Fapp-settings%60%2C%20with%20a%20generated%20secret%20key%2C%20ProxyFix%20for%20the%20forwarded%20headers%2C%20and%20gunicorn%20workers%20sized%20to%20the%20VM.%0A-%20SQLite%20in%20WAL%20mode%20at%20%60~%2Fdata%2Fapp.db%60%20%28or%20the%20app%27s%20own%20database%29%2C%20with%20Flask%27s%20static%20folder%20served%20by%20nginx.%0A-%20The%20owner%27s%20exe.dev%20email%20in%20%60FLASK_ADMIN_EMAILS%60%2C%20and%20a%20new%20app%20that%20signs%20visitors%20in%20from%20the%20%60X-ExeDev-Email%60%20header.%0A-%20Nightly%20backups%20in%20%60~%2Fbackups%60%2C%20with%20a%20first%20one%20taken%20and%20checked.%0A%0ARead%20the%20whole%20recipe%2C%20including%20the%20closed%20details%2C%20and%20follow%20%22Set%20it%0Aup%20by%20hand%22%20in%20order%2C%20skipping%20%22Create%20the%20VM%22%3B%20the%20walkthrough%20above%20it%0Ais%20for%20the%20owner.%20REPO%3Dnew%20takes%20%22Start%20a%20new%20app%22%3B%20anything%20else%20takes%0A%22Bring%20your%20repository%22.%20If%20cloning%20from%20GitHub%20fails%2C%20the%20repository%20is%0Aprivate%3A%20give%20the%20owner%20the%20%60ssh%20exe.dev%20integrations%20add%20github%60%20command%0Afrom%20that%20step%2C%20with%20this%20VM%27s%20name%20and%20the%20repository%2C%20wait%20for%20them%2C%0Aand%20clone%20from%20github.int.exe.xyz.%0ANever%20overwrite%20an%20existing%20~%2Fapp.env.%20Don%27t%20commit%20to%20the%20owner%27s%0Arepository%20or%20push%20to%20its%20origin.%20If%20their%20app%20doesn%27t%20fit%20%28no%20factory%0Aor%20%60app%60%20object%20Flask%20can%20find%2C%20settings%20read%20from%20other%20variable%20names%2C%0Aa%20different%20database%29%2C%20set%20FLASK_APP%20and%20~%2Fapp.env%20to%20fit%20it%20and%20tell%0Athe%20owner%20what%20you%20changed%20and%20what%20their%20code%20should%20read.%0ALeave%20the%20VM%20private%20and%20don%27t%20reboot%3A%20check%20that%20app.service%2C%20nginx%20and%0Aapp-backup.timer%20are%20enabled%20instead.%20Skip%20the%20later%20Restore%20and%20Update%0Ainstructions%3B%20the%20restore%20check%20in%20setup%20uses%20a%20scratch%20copy%20only.%20Don%27t%0Aturn%20on%20the%20optional%20timers%2C%20worker%2C%20or%20LLM%20endpoint%20unless%20asked.%0AGive%20the%20owner%20https%3A%2F%2F%3Cvm%3E.exe.xyz%2F%20and%2C%20of%20the%20two%20commands%20at%20the%0Aend%2C%20the%20one%20that%20fits%20REPO.%0A%0AFinish%20with%20the%20URLs%20I%20should%20open%20and%20these%20commands%2C%20which%20only%20I%20can%20run%2C%20from%20my%20own%20computer%20%28with%20this%20VM%27s%20name%20in%20them%29%3A%0A%20%20ssh%20my-flask.exe.xyz%20deploy%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20after%20each%20git%20push%20to%20GitHub%0A%20%20git%20clone%20my-flask.exe.xyz%3Asrc%20my-flask%20%20%20%20%20%23%20if%20you%20started%20a%20new%20app%20and%20it%20isn%27t%20on%20GitHub%20yet%0A to create a VM whose agent, Shelley, follows this recipe. From a terminal:

```sh
curl -fsSL https://exe-staging.dev/deploy/flask/prompt.txt | ssh exe.dev new --prompt=/dev/stdin
```

Then, on your own computer:

```sh
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
```

Or follow the steps below by hand.

Your 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](https://flask.palletsprojects.com/en/stable/deploying/)
describe: [gunicorn](https://gunicorn.org) behind nginx, with
[uv](https://docs.astral.sh/uv/) installing Python and your dependencies.

## 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](#whos-signed-in) 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:

```bash
git push origin main
ssh my-flask.exe.xyz deploy
```

It prints:

```text
-----> 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](#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:

```bash
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](#bring-your-repository) and add it to `~/src` as
`origin`; `deploy` then pulls from there.

### Run it on your computer

In your checkout:

```bash
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](https://flask.palletsprojects.com/en/stable/deploying/proxy_fix/):

```python
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`, where
  [`from_prefixed_env()`](https://flask.palletsprojects.com/en/stable/config/#configuring-from-environment-variables)
  turns `FLASK_SECRET_KEY` into `SECRET_KEY`. Edit, then
  `sudo 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](/docs/login-with-exe)). `myapp/auth.py` reads it:

```python
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:

```bash
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](https://flask-sqlalchemy.readthedocs.io/)
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](https://flask-migrate.readthedocs.io/) migration on
your computer:

```bash
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](/deploy/postgres#run-it-next-to-your-app), and
`uv add "psycopg[binary]"` in your project. Then, on the VM, swap in its
`DATABASE_URL` and deploy, which creates the tables:

```bash
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:

```bash
scp -r my-flask.exe.xyz:backups my-flask-backups
```

They hold your secret key, so keep them private.
[Back up and restore](#back-up-and-restore) has the rest.

## Background jobs

**On a schedule**: a
[Flask CLI command](https://flask.palletsprojects.com/en/stable/cli/#custom-commands)
and a systemd timer. The new app's `app-flask digest --send` emails the
day's notes through exe.dev's [email gateway](/docs/send-email); see
[Run a job on a schedule](#run-a-job-on-a-schedule).

**After a request**: for work it shouldn't wait for, queue a job with
[RQ](https://python-rq.org) on [Redis](/deploy/redis#run-it-next-to-your-app);
see [Queue jobs with RQ](#queue-jobs-with-rq). `deploy` restarts the
worker with the app.

## Call an LLM

From the VM, exe.dev's [LLM gateway](/docs/integrations-llm) 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:

```python
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:

```bash
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](/docs/integrations-http-proxy)
holds the key at exe.dev and adds it to each request. On your computer:

```bash
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](/deploy/agent-secrets)).

## Share it, or make it public

To open the app to everyone, on your computer:

```bash
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](/docs/cnames)), then on
your computer:

```bash
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:

```bash
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](/docs/integrations-github), and deploys. For a
safer loop, give it a [second VM](/deploy/dev-test-prod) 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.

<details id="create-the-vm" data-manual-setup class="dp-details">
<summary>Set it up by hand</summary>

### Create the VM

On your computer (pick another name if `my-flask` is taken):

```bash
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.

```bash
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:

```bash
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](/docs/integrations-github) instead, so no token
lands on the VM. On your computer:

```bash
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:

```bash
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:

```bash
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:

```bash
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`:

```bash
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`:

```bash
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](#whos-signed-in):

```bash
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`:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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).

```bash
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:

```bash
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?](#no-github)). The push is refused if someone has
uncommitted changes there:

```bash
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.

```bash
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:

```bash
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:

```bash
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](/docs/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.

```bash
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:

```bash
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:

```bash
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.

```bash
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](#open-your-app).

</details>

<details id="deploy-on-push" class="dp-details">
<summary>Deploy on push</summary>

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:

```bash
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>`.

</details>

<details id="run-a-job-on-a-schedule" class="dp-details">
<summary>Run a job on a schedule</summary>

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:

```bash
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`.

</details>

<details id="queue-jobs-with-rq" class="dp-details">
<summary>Queue jobs with RQ</summary>

Set up Redis with the [Redis page](/deploy/redis#run-it-next-to-your-app),
which adds a `REDIS_URL` line to `~/app.env`. Then add RQ to your project, on your
computer:

```bash
uv add rq
```

The job is a plain function, `myapp/tasks.py`:

```python
"""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:

```python
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:

```bash
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.

</details>

<details id="back-up-and-restore" class="dp-details">
<summary>Back up and restore</summary>

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](#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:

```bash
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:

```bash
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:

```bash
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](#create-the-vm) from **The deploy
command** to the end; its **Deploy** step starts the app. Set up any
worker or timers again as in [Background jobs](#background-jobs). For a
copy of the whole VM instead, run `ssh exe.dev cp my-flask my-flask-2` on
your computer.

</details>

<details id="update" class="dp-details">
<summary>Update Flask, Python, and uv</summary>

Flask and your other dependencies are pinned in your project's
`uv.lock`, so updates are commits. In your project, on your computer:

```bash
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](https://flask.palletsprojects.com/en/stable/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:

```bash
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`.

</details>

<details id="troubleshooting" class="dp-details">
<summary>Something not working?</summary>

On the VM, start with the logs:

```bash
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 app` shows why: usually an import error, or a setting
  missing from `~/app.env`.
- **`Could not locate a Flask application`** during a deploy: `FLASK_APP`
  in `~/app.env` doesn't match your code. It takes what `flask --app`
  does: a module (`app`), a package with `create_app` (`myapp`), or
  `module:name`.
- **`deploy` stops at "Pulling"**: `~/src` has local changes or commits
  GitHub doesn't. `git -C ~/src status` shows which; commit and push
  them, or `git -C ~/src reset --hard origin/main` to drop them.
- **Links and redirects say `http://`**: the app isn't behind ProxyFix.
  Check `app.service` starts gunicorn with
  `~/app-settings/gunicorn.conf.py`, which loads `wsgi.py`.
- **No `X-ExeDev-Email` on a public site**: visitors who haven't signed
  in don't send it. Send them to `/__exe.dev/login?redirect=/`, as
  `@login_required` does.
- **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](#background-jobs).
- **Static files are 404**: `ls -l ~/app/.nginx` should show `static`
  linked to your app's static folder. An app whose static URL isn't
  `/static` is served by Flask instead.
- **413 Request Entity Too Large**: raise `client_max_body_size` in
  `/etc/nginx/sites-available/app`, then `sudo systemctl reload nginx`.
- **A worker was killed with `WORKER TIMEOUT`**: a request took more than
  30 seconds without its thread letting go. Raise `timeout` in
  `gunicorn.conf.py`, or move the work to RQ.

</details>

## 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](/deploy/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](https://exe.dev/pricing)), and one VM can run several small apps.


## Related

- [Deploy a Django app](https://exe-staging.dev/deploy/django.md): Your Django app on a computer of its own. git push to deploy.
- [Deploy a FastAPI app](https://exe-staging.dev/deploy/fastapi.md): Your API on a VM of its own. Push to deploy; the data stays put.
- [Self-host PostgreSQL](https://exe-staging.dev/deploy/postgres.md): Your own Postgres on a real disk, with backups you've actually restored.
- [Self-host Redis](https://exe-staging.dev/deploy/redis.md): Your own Redis on a real disk, private by default, with backups you've restored.
- [Migrate a Heroku app to exe.dev](https://exe-staging.dev/deploy/migrate-heroku.md): Your Procfile, config vars, and Postgres on a VM of your own.
- [Give agents API access without giving them the keys](https://exe-staging.dev/deploy/agent-secrets.md): Your agents call your APIs. The keys stay with exe.dev, outside the VM.
