coreapp new --postgres: apps with their own database

A template overlay (templates/postgres) adds DEPENDS="postgresql", DB_*
settings with a random password, an install that creates the user and
database on the Core's PostgreSQL (safe to re-run), an uninstall that
drops them, and a Python example that counts visits. Tested with a
throwaway app: deploy, redeploy and a reboot of the Core keep the data,
remove drops the database and user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:06:55 -07:00
co-authored by Claude Opus 5.5
parent 1108060432
commit 74bdc13f0f
12 changed files with 211 additions and 9 deletions
+1
View File
@@ -0,0 +1 @@
www
+9
View File
@@ -0,0 +1,9 @@
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION>
# and copies it to the Core. Replace this with your own app; keep it
# listening on the port in docker-compose.yml.in (8080).
FROM python:3.13-slim
RUN pip install --no-cache-dir "psycopg[binary]==3.2.*"
COPY app.py /app/app.py
USER nobody
EXPOSE 8080
CMD ["python", "-u", "/app/app.py"]
+13
View File
@@ -0,0 +1,13 @@
## Database
The app has its own database on the Core's shared PostgreSQL
(`DEPENDS="postgresql"` in `service`):
- `install` creates the user and database `{{DBNAME}}`, with the random
`DB_PASSWORD` from `.env`; `uninstall` drops both (`coreapp remove`
deletes the data).
- The app reads `DB_HOST` (`postgresql.<domain>`, which only resolves on the
Core's `core` network), `DB_PORT`, `DB_NAME`, `DB_USER` and `DB_PASSWORD`
from its environment. `app.py` shows how, with `psycopg`.
- Look at the data: `coreapp-vm ssh docker exec -it postgresql psql -U postgres {{DBNAME}}`.
+82
View File
@@ -0,0 +1,82 @@
"""{{TITLE}}: counts its visits in its PostgreSQL database.
Settings come from the environment (.env on the Core): DB_HOST, DB_PORT,
DB_NAME, DB_USER, DB_PASSWORD, APP_URL.
"""
import html
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import psycopg
DB = {
"host": os.environ["DB_HOST"],
"port": os.environ.get("DB_PORT", "5432"),
"dbname": os.environ["DB_NAME"],
"user": os.environ["DB_USER"],
"password": os.environ["DB_PASSWORD"],
"connect_timeout": 5,
}
def connect():
return psycopg.connect(**DB, autocommit=True)
def setup():
# PostgreSQL may still be starting (after a reboot): keep trying
for attempt in range(60):
try:
with connect() as db:
db.execute(
"CREATE TABLE IF NOT EXISTS visits ("
" id bigserial PRIMARY KEY,"
" at timestamptz NOT NULL DEFAULT now())"
)
return
except psycopg.OperationalError as error:
print(f"Waiting for the database ({error})", flush=True)
time.sleep(5)
raise SystemExit("The database didn't answer for 5 minutes")
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.reply(200, "text/plain", "ok\n")
return
try:
with connect() as db:
db.execute("INSERT INTO visits DEFAULT VALUES")
count = db.execute("SELECT count(*) FROM visits").fetchone()[0]
except psycopg.Error as error:
self.reply(503, "text/plain", f"Database error: {error}\n")
return
page = f"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{TITLE}}</title></head>
<body>
<h1>{{TITLE}}</h1>
<p>Running on Federated Core, deployed with coreapp-dev.</p>
<p>Visits, counted in PostgreSQL: <strong id="visits">{count}</strong></p>
<p>{html.escape(os.environ.get("APP_URL", ""))}</p>
</body>
</html>
"""
self.reply(200, "text/html; charset=utf-8", page)
def reply(self, status, content_type, body):
data = body.encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
if __name__ == "__main__":
setup()
print("Listening on port 8080", flush=True)
ThreadingHTTPServer(("", 8080), Handler).serve_forever()
+11
View File
@@ -0,0 +1,11 @@
# Filled in once, when the app is installed (see README.md). Redeploying
# keeps the result, so secrets don't change.
IMAGE_VERSION=@VERSION@
APP_URL=https://{{NAME}}.@DOMAIN@
APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@
# Its database on the Core's PostgreSQL, made by install
DB_HOST=postgresql.@DOMAIN@
DB_PORT=5432
DB_NAME={{DBNAME}}
DB_USER={{DBNAME}}
DB_PASSWORD=@DB_PASSWORD:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@
+18
View File
@@ -0,0 +1,18 @@
. /federated/lib/helpers.sh
installGeneric {{NAME}}
# .env holds secrets
chmod 600 /federated/apps/{{NAME}}/.env
# Its own database and user on the Core's PostgreSQL (DEPENDS=postgresql),
# with the password from .env. Safe to run again: an existing user gets the
# password, an existing database is kept.
DB_PASSWORD="$(sed -n 's/^DB_PASSWORD=//p' /federated/apps/{{NAME}}/.env)"
if docker exec postgresql psql -U postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname = '{{DBNAME}}'" | grep -q 1; then
docker exec postgresql psql -U postgres -qc "ALTER USER {{DBNAME}} WITH PASSWORD '$DB_PASSWORD'"
else
docker exec postgresql psql -U postgres -qc "CREATE USER {{DBNAME}} WITH PASSWORD '$DB_PASSWORD'"
fi
if ! docker exec postgresql psql -U postgres -tAc "SELECT 1 FROM pg_database WHERE datname = '{{DBNAME}}'" | grep -q 1; then
docker exec postgresql psql -U postgres -qc "CREATE DATABASE {{DBNAME}} OWNER {{DBNAME}}"
fi
unset DB_PASSWORD
+9
View File
@@ -0,0 +1,9 @@
NAME="{{TITLE}}"
DESCRIPTION="{{TITLE}}, made with coreapp-dev"
DOCS=
CONTAINER=coreapp/{{NAME}}
VERSION=0.1.0
INTERNAL_IP={{IP}}
DEPENDS="postgresql"
PORTS=8080
MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx"
+6
View File
@@ -0,0 +1,6 @@
# Sourced by the Core's uninstallapp (so no `exit` here): stop the app and
# delete its settings, data and database
docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down
rm -rf /federated/apps/{{NAME}}
docker exec postgresql psql -U postgres -qc "DROP DATABASE IF EXISTS {{DBNAME}}"
docker exec postgresql psql -U postgres -qc "DROP USER IF EXISTS {{DBNAME}}"