Skip to content

How to run a SQLite app on DigitalOcean

Run the app as a systemd user unit that requires Litebackup, so a Droplet that shuts down hands its database to the next one and every version reaches your Spaces bucket.

Run the app as a systemd user unit after Litebackup

[Unit]
Description=App
After=litebackup.service
Requires=litebackup.service

[Service]
Environment=DATABASE=/var/lib/app/app.sqlite
ExecStartPre=%h/.local/bin/litebackup acquire app.sqlite /var/lib/app/app.sqlite --lock-timeout 5m
ExecStart=/usr/bin/python3 %h/app.py
TimeoutStartSec=6min
Restart=on-failure
RestartSec=2

[Install]
WantedBy=default.target

Questions

Why is the app a user unit?

litebackup install service, run as an ordinary user, installs a systemd user service, and systemd orders units only within one manager. Running the app as a user unit of the same user lets After and Requires stop the app before Litebackup drains.

What happens if a Droplet loses power?

The app gets no signal, so nothing drains. Writes up to the last sync are on your server, and the next Droplet acquires the database once the old session's lease lapses, about a minute by default.

Can the server and the bucket be in the same region?

Only if the server Droplet reaches that region's Spaces endpoint at a public address. Inside DigitalOcean, the endpoint for the Droplet's own region and some nearby ones resolve to a private address, which Litebackup does not connect to. Check the endpoint from the server Droplet before you create the bucket.

Do the app and the server need separate Droplets?

Yes. The server holds every version of each database and should outlive any app Droplet. Several app Droplets can join one server, each with its own databases or taking turns with the same one.

What runs where

  • Server Droplet

    Runs your Litebackup server, which keeps recent versions on its disk and the console at its HTTPS address.

  • Spaces bucket

    Holds every archived version, encrypted with your server's key before it leaves the Droplet.

  • App Droplet

    Runs the Litebackup client and your app as user units of one user, the app after the client.

A Droplet shutdown sends TERM to the app's user unit, systemd stops the app before litebackup.service, which syncs and releases the database to the Litebackup server on its own Droplet, the server stores versions in a Spaces bucket, and a new Droplet acquires the database

Install the Litebackup server on a Droplet

Run the server on a Droplet of its own. Follow Litebackup on DigitalOcean to create it from the Marketplace app or from a Debian 13 image, then run the installer on it and open the setup link it prints.

# Install the Litebackup server. Run this on the server Droplet.
curl --fail --silent --show-error --location https://litebackup.com/server.sh | bash

Create a Spaces bucket for the server

Your server keeps recent versions on its own disk and archives every version, encrypted, to a bucket. Inside DigitalOcean, some Spaces endpoints resolve to a private address, and Litebackup does not connect a bucket at a private address. A Droplet in NYC3, for example, reaches the NYC3, TOR1, and ATL1 endpoints at a private address. Before you pick the region, check it from the server Droplet.

# Show the address the server Droplet uses for a Spaces region's endpoint.
getent ahostsv4 sfo3.digitaloceanspaces.com

If the address starts with 10., choose another region. Then create the bucket and a key for it in the control panel.

  1. Open Spaces Object Storage and create a bucket in that region.
  2. On the Access Keys tab, choose Create Access Key, select Limited access, tick the bucket, and give it Read/Write/Delete. Copy the secret, which is shown only once.
  3. Open your server's setup link, sign in, and connect an S3-compatible bucket with the endpoint https://REGION.digitaloceanspaces.com, the region, the bucket's name, and the key.

Spaces costs $5 a month for 250 GiB of storage and 1,024 GiB of outbound transfer across your buckets, then $0.02 per GiB stored and $0.01 per GiB transferred (Spaces pricing).

Prepare the app Droplet

Create another Droplet for the app, from the Debian 13 image. Connect as root and create the user that runs the app and owns its database. Lingering starts that user's systemd manager at boot, so the app starts without anyone signing in.

# Create the user that runs the app and owns its database, and start its
# systemd manager at boot.
useradd --create-home --shell /bin/bash app
loginctl enable-linger app
install --directory --owner app --group app --mode 0750 /var/lib/app
# Let the app user sign in over SSH with your key.
install --directory --owner app --group app --mode 0700 /home/app/.ssh
install --owner app --group app --mode 0600 \
    /root/.ssh/authorized_keys /home/app/.ssh/authorized_keys

Join the Droplet as the app user

Connect again as that user with ssh app@YOUR_DROPLET_IP. Install the litebackup command, then install its service with a join token from Machines → Add machine in your console. Use a regular token here, not an ephemeral one. Stopping the service drains, which removes an ephemeral machine, and the service does not keep the token it would need to join again after a reboot.

# Install the litebackup command for the app user.
curl --fail --silent --show-error --location https://litebackup.com/cli.sh | bash
# Join your server and start the Litebackup client as this user's service.
~/.local/bin/litebackup install service --api-key 'YOUR_JOIN_TOKEN@HOST'

The service is the systemd user unit litebackup.service. It starts at boot, and when it stops it syncs every database it holds, releases them, and then exits.

Run the app as a user unit

Save the unit below as ~/.config/systemd/user/app.service, with the app at ~/app.py.

[Unit]
Description=App
After=litebackup.service
Requires=litebackup.service

[Service]
Environment=DATABASE=/var/lib/app/app.sqlite
ExecStartPre=%h/.local/bin/litebackup acquire app.sqlite /var/lib/app/app.sqlite --lock-timeout 5m
ExecStart=/usr/bin/python3 %h/app.py
TimeoutStartSec=6min
Restart=on-failure
RestartSec=2

[Install]
WantedBy=default.target

Requires= and After= start the app after the Litebackup client and stop it before the client. Stopping litebackup.service, or shutting the Droplet down, therefore sends TERM to the app first and drains once it has exited. ExecStartPre acquires the database before the app opens it and waits up to 5 minutes while another Droplet holds it, which TimeoutStartSec allows for. At boot the app can start a moment before the client accepts connections, so the acquire fails once and Restart=on-failure starts it again 2 seconds later.

# Start the app now and at every boot.
systemctl --user daemon-reload
systemctl --user enable --now app

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.

# 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()

Restart the app on its own first. It records a row, acquires the database it already holds, and prints that row.

# Restart the app and read the shutdown log.
systemctl --user restart app
curl http://127.0.0.1:8080/

Next, hand the database to a second Droplet. Prepare it the same way. Its app waits in ExecStartPre while the first Droplet holds the lock. Then stop the Litebackup client on the first Droplet, which stops its app first.

# On the first Droplet, stop the app and drain the database.
systemctl --user stop litebackup.service

The second Droplet's app starts within seconds and prints the first Droplet's row. A Droplet shutdown takes the same path, because systemd stops the user units in order. Shut down the Droplet that now runs the app with doctl from your computer, then run systemctl --user start app on the first Droplet and read the log again.

# Shut the Droplet down gracefully and wait until it is off.
doctl compute droplet-action shutdown YOUR_DROPLET_ID --wait

A Droplet that loses power stops without a drain. The next Droplet's acquire waits for the old session's lease to lapse, about a minute by default, and then starts the app with every write your server received before the power was cut.

Next steps

For instances that come and go, see SQLite on autoscaled machines. A Rails app can acquire and drain from Puma instead of a unit, as in Rails SQLite backup. The command line reference covers litebackup acquire, release, and drain.

Install

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