# How to run a SQLite app on Fly.io

Make litebackup run your image's entrypoint and set kill_signal to SIGTERM, so a Machine acquires its database when it starts and drains it before Fly stops it.

## Run your Fly Machine under litebackup run

### fly.toml

```text
app = "YOUR_APP"
primary_region = "iad"
kill_signal = "SIGTERM"
kill_timeout = 60

[build.args]
  LITEBACKUP_SHA256 = "YOUR_LITEBACKUP_SHA256"

[mounts]
  source = "app_data"
  destination = "/data"

[http_service]
  internal_port = 8080
  force_https = true
  auto_stop_machines = "off"
```

### Dockerfile

```text
ENTRYPOINT ["litebackup", "run", "--acquire", "app.sqlite=/data/app.sqlite", "--"]
CMD ["python3", "/app/app.py"]
```

## Questions

### Why change kill_signal to SIGTERM?

Fly sends SIGINT by default. litebackup run forwards it, but many app servers, and the test app on this page, shut down cleanly only on SIGTERM. kill_timeout then gives the app and the drain time to finish.

### What if a Machine is killed before the drain finishes?

Writes up to the last sync are on your server. The next Machine waits for the old session's lease to lapse, about a minute by default, then acquires the database with those writes. Raise kill_timeout if your app needs longer to exit.

### Does the volume still matter?

It keeps the database and the client's state next to the Machine, so the app reads and writes a local file and a restart fetches only what changed. Your server and bucket hold every version, so a lost volume costs a download, not your data.

### Can I run more than one Machine?

One Machine writes a database at a time. Use separate databases for separate Machines, or read replicas for reads, and keep a single writer for each database.

## What each setting does

- **kill_signal**. Sends SIGTERM instead of SIGINT, so the app shuts down cleanly.
- **kill_timeout**. Gives the app and the drain up to the seconds you set, at most 300, before Fly kills the Machine.
- **mounts**. Keeps the database and the client's state on a volume at /data.
- **LITEBACKUP_API_KEY**. Joins the Machine to your server, set as a Fly secret.

![fly deploy or fly machine stop sends SIGTERM to litebackup run, the Machine's entrypoint, which forwards it to the app and, once the app exits, syncs and releases the database to the Litebackup server within kill_timeout, while the volume holds the database and the client state](https://litebackup-cdn.com/media/5d5f21e7e245fa23-fly-io-1400.webp)

## Install your Litebackup server

Fly Machines come and go with each deploy, so run your Litebackup server on a machine that stays, from the [install guide](/install). Then create a join token for your Machines. An ephemeral token suits them, because a Machine that drains is removed from the server instead of piling up in your machine list.

```bash
# Create a join token for Fly Machines. Run this on your Litebackup server.
litebackup server join-token create --name fly --ephemeral --uses 0 --lifetime 30d
```

## Make litebackup run the entrypoint

Add the pinned `litebackup` command to your image and put `litebackup run` in front of your app's command. The Dockerfile below runs the small Python app from the shutdown test further down, so replace `CMD` and the `COPY` line with your own app.

```dockerfile
# syntax=docker/dockerfile:1.10
FROM python:3.13-slim
ARG TARGETARCH
ARG LITEBACKUP_VERSION=1.20.0
ARG LITEBACKUP_SHA256
ADD --chmod=0755 --checksum=sha256:${LITEBACKUP_SHA256} \
    https://litebackup-cdn.com/litebackup/${LITEBACKUP_VERSION}/litebackup-linux-${TARGETARCH} \
    /usr/local/bin/litebackup
COPY app.py /app/app.py
# Keep the client's identity and state on the volume with the database.
ENV XDG_STATE_HOME=/data/state
ENTRYPOINT ["litebackup", "run", "--acquire", "app.sqlite=/data/app.sqlite", "--"]
CMD ["python3", "/app/app.py"]
```

`litebackup run` acquires `app.sqlite` before your app starts, waiting while a previous Machine still holds it. It forwards Fly's stop signal to the app, and once the app exits it syncs the database to your server and releases it. `XDG_STATE_HOME` puts the client's state on the volume next to the database, so a Machine that restarts with the same volume only fetches what changed.

Fly Machines run on amd64 unless you choose otherwise. Look up the checksum for that executable and put it in `fly.toml` below.

```bash
# Look up the SHA-256 of the 1.20.0 Linux executable in the release metadata.
LITEBACKUP_SHA256="$(curl --fail --silent --show-error --location \
    https://litebackup.com/pkg/metadata \
    | jq --raw-output '.packages[] | select(.slug == "cli") | .releases[]
        | select(.version == "1.20.0") | .artifacts[]
        | select(.name == "litebackup-linux-amd64") | .sha256')"
echo "${LITEBACKUP_SHA256}"
```

## Configure fly.toml

```toml
app = "YOUR_APP"
primary_region = "iad"
kill_signal = "SIGTERM"
kill_timeout = 60

[build.args]
  LITEBACKUP_SHA256 = "YOUR_LITEBACKUP_SHA256"

[mounts]
  source = "app_data"
  destination = "/data"

[http_service]
  internal_port = 8080
  force_https = true
  auto_stop_machines = "off"
```

Fly sends SIGINT by default and kills a Machine 5 seconds later. `kill_signal = "SIGTERM"` sends the signal most apps treat as a request to shut down, and `kill_timeout`, in seconds and at most 300, gives the app time to exit and `litebackup run` time to drain. Fly uses both when `fly deploy` replaces a Machine and when you run `fly machine stop`. Keep `auto_stop_machines` at `"off"`, its default, or set it to `"stop"`, which sends the same signal.

A volume belongs to one Machine in one region, and one Machine writes the database at a time. Run one Machine for this app, and use [read replicas](/sqlite-replication) or separate databases when you need more.

## Create the volume and the secret

```bash
# Create the app, its volume, and the join token secret.
fly apps create YOUR_APP
fly volumes create app_data --region iad --size 1
fly secrets set LITEBACKUP_API_KEY='YOUR_JOIN_TOKEN@HOST'
```

Use the region from `primary_region`. Fly keeps the secret encrypted and sets it as `LITEBACKUP_API_KEY` in the Machine, where `litebackup run` joins with it on the first start and again after a drain removed the machine. `litebackup run` removes it from your app's environment.

## Deploy

```bash
# Build the image, start the Machine, and follow its logs.
fly deploy
fly logs
```

The logs show `event=acquire` and then `event=started` from `litebackup run` before your app's own output. The console lists the database under the name `app.sqlite`, with the Machine as its writer.

## Test a shutdown the way the platform does it

To check that the drain finishes before the platform kills the old instance, the app below records a row with its host name when it receives TERM and prints the newest row when it starts. When the next instance prints the row the previous one wrote as it stopped, that row reached the new instance through your server.

```python
# Serve the shutdown log, and record a row when the platform stops the app.
import os
import signal
import socket
import sqlite3
import sys
from datetime import datetime, timezone
from wsgiref.simple_server import make_server

DATABASE = os.environ.get("DATABASE", "/data/app.sqlite")

database = sqlite3.connect(DATABASE)
database.execute("CREATE TABLE IF NOT EXISTS shutdowns (host TEXT, stop_time TEXT)")
last = database.execute("SELECT host, stop_time FROM shutdowns ORDER BY rowid DESC LIMIT 1").fetchone()
print("last shutdown", last, file=sys.stderr)


def stop(signal_number, frame):
    database.execute(
        "INSERT INTO shutdowns VALUES (?, ?)",
        (socket.gethostname(), datetime.now(timezone.utc).isoformat()),
    )
    database.commit()
    database.close()
    sys.exit(0)


def shutdown_log(environ, start_response):
    rows = database.execute("SELECT host, stop_time FROM shutdowns ORDER BY rowid").fetchall()
    start_response("200 OK", [("Content-Type", "text/plain")])
    return ["".join(f"{host} {stop_time}\n" for host, stop_time in rows).encode()]


signal.signal(signal.SIGTERM, stop)
make_server("", int(os.environ.get("PORT", "8080")), shutdown_log).serve_forever()
```

Save it as `app.py` next to the Dockerfile and deploy. Then stop the Machine the way a deploy does and start it again.

```bash
# Stop the Machine with kill_signal, start it again, and read the shutdown log.
fly machine stop YOUR_MACHINE_ID
fly machine start YOUR_MACHINE_ID
curl https://YOUR_APP.fly.dev/
```

The log ends with a row from the Machine you stopped, and `fly logs` shows `event=signal signal=TERM`, `event=exited`, and `event=drain` from that stop. A `fly deploy` takes the same path. To prove the copy on your server rather than on the volume, restore `app.sqlite` from the console into a new file on another machine and query it, as in [point-in-time restore](/sqlite-point-in-time-restore).

## Next steps

The same entrypoint works on other platforms that stop containers with a signal, as [SQLite on autoscaled machines](/sqlite-autoscaling) explains. For a Rails app on Fly.io, add the Railtie from [Rails SQLite backup](/rails-sqlite-backup). The [command line reference](/cli) lists every `litebackup run` flag.

## Install

[Install your Litebackup server](/install) on a Linux machine you control, then join your first machine with the [command line](/cli) or an [SDK](/sdk). The [deployment guides](/sqlite-deployment-guides) cover each platform. Keep a second, independent backup of data you cannot lose, so no single system holds the only copy.
