Skip to content

Latest commit

 

History

History
229 lines (187 loc) · 11.7 KB

docker.md

File metadata and controls

229 lines (187 loc) · 11.7 KB

Run Ledgerly with Docker

This packages the backend and built receipt UI for local testing and Lightsail. The base Compose file keeps FastAPI on host loopback. The production overlay adds Caddy HTTPS; OpenClaw runs separately as a loopback-only systemd user service. These files configure existing infrastructure but do not create AWS resources. Use Docker Desktop with Linux containers on Windows, or Docker Engine with the Compose plugin on an x86-64 Ubuntu host. Compose targets linux/amd64. The commands below use ~/Ledgerly for a fresh server checkout. If an existing server checkout has a different directory name, run them from that checkout; renaming the GitHub repository does not move a local directory. Keep the expense-agent Compose project name so its existing receipt and OCR volumes remain attached. Paddle's memory needs must be measured on the target machine; a passing health check does not prove that OCR models fit in RAM.

The current application migrates supported SQLite databases through schema v10 on first use. Create the database-and-evidence backup below before replacing an older image; an older app image cannot read the upgraded schema.

First local run (PowerShell)

Stop the existing Uvicorn process with Ctrl+C. Keep your existing .env and keys; do not replace it with the empty example. New users can copy .env.example once and fill its keys. Docker gets keys at runtime; neither keys nor .env enter the image. Ensure Docker Desktop is running, then from the repository directory:

docker version
docker compose version
docker compose config --quiet
docker compose build api
docker compose up -d --wait --wait-timeout 120
docker compose ps

Avoid plain docker compose config when sharing output: it can expand secrets. Builds download Python packages, Linux packages and base images. Both PaddleOCR and Tesseract are installed. The initial build is substantial and needs network access. Existing dependency ranges are retained; this image is not yet a fully locked/reproducible release. Keep known-good images until replacements pass tests.

Visit http://127.0.0.1:8000/docs, supply the saved APP_API_KEY, and upload as before. OCR_ENGINE=paddle remains the default; switch to tesseract in .env and recreate the service with docker compose up -d --force-recreate api. Compose overrides TESSERACT_CMD, DATABASE_PATH, UPLOAD_DIR, and PADDLE_DEVICE with Linux paths/CPU settings, so Windows paths in .env are safe. Do not change them to Windows paths inside the container.

Add API_PORT=8001 to .env if you need your old local server running too; use port 8001 in the browser. Set API_DOCS_ENABLED=false to disable /docs, /redoc and /openapi.json. Recreate the container after environment changes. This only hides documentation; every protected API still requires the application key.

What persists

Compose creates named volumes expense-agent_receipt-data and expense-agent_paddle-cache. They hold /app/data (SQLite and receipt uploads) and /home/expense (Paddle/PaddleX and other OCR caches). New volumes inherit the image's directory ownership for UID/GID 10001. Do not change the Compose project name or volume definitions casually; a different project name uses new volumes.

Your existing Windows data/ directory is not automatically imported. The container begins with a new database. Keep the original files. This avoids overwriting existing receipts. A deliberate migration can be performed later.

docker compose down stops/removes containers but keeps these volumes. Do not use docker compose down -v or prune volumes containing receipts: those operations delete the database, uploads and caches. Volumes survive container replacement, not deletion of the Lightsail disk/instance. Back up separately.

Production backup

Use SQLite's online backup API so the database copy represents one consistent snapshot. Perform this during a controlled quiet period with no receipt, statement, amendment or lifecycle writes while the database and uploads are copied. Run these commands from the existing server checkout, even if its local directory still has the old repository name. Set one timestamp and keep using it throughout:

BACKUP_TS="$(date -u +%Y%m%dT%H%M%SZ)"
BACKUP_DIR="$HOME/ledgerly-backups/$BACKUP_TS"
install -d -m 700 "$BACKUP_DIR"
docker compose -f compose.yaml -f compose.production.yaml exec -T api python -c "import sqlite3; source=sqlite3.connect('/app/data/expenses.db'); backup=sqlite3.connect('/app/data/expenses-backup-${BACKUP_TS}.db'); source.backup(backup); backup.close(); source.close()"
docker compose -f compose.yaml -f compose.production.yaml cp "api:/app/data/expenses-backup-${BACKUP_TS}.db" "$BACKUP_DIR/expenses.db"
docker compose -f compose.yaml -f compose.production.yaml cp api:/app/data/uploads "$BACKUP_DIR/uploads"

Verify before archiving:

python3 -c "import os, sqlite3; path='$BACKUP_DIR/expenses.db'; db=sqlite3.connect(path); print('Bytes:', os.path.getsize(path)); print('Integrity:', db.execute('PRAGMA integrity_check').fetchone()[0]); print('Receipts:', db.execute('SELECT COUNT(*) FROM receipts').fetchone()[0]); db.close()"
ARCHIVE="$HOME/ledgerly-backups/ledgerly-mvp-${BACKUP_TS}.tar.gz"
tar -C "$HOME/ledgerly-backups" -czf "$ARCHIVE" "$BACKUP_TS"
chmod 600 "$ARCHIVE"
sha256sum "$ARCHIVE" > "${ARCHIVE}.sha256"
chmod 600 "${ARCHIVE}.sha256"
sha256sum -c "${ARCHIVE}.sha256"

Copy the archive and checksum to a protected off-instance destination. A Lightsail snapshot is an additional recommended recovery layer. Only then remove the temporary /app/data/expenses-backup-${BACKUP_TS}.db copy. The portable archive deliberately excludes .env, SSH keys and service tokens. The checksum detects corruption; encrypt the off-instance destination because the archive itself is not encrypted by these commands.

Automated checks without gateway credits

The standard test suite runs in a dedicated test image, with no real keys, no access to your receipt volumes, and no network while the tests run:

docker compose -f compose.test.yaml up --build --abort-on-container-exit --exit-code-from tests
docker compose -f compose.test.yaml down

The exit code of the first command is the test result. This includes native Paddle imports/tensor computation and a real Tesseract upload using a generated PNG. LLM calls are mocked. Full Paddle OCR inference is not tested here because it requires downloading model weights; test that separately with one receipt.

After building the runtime image, test container recreation and persistent data:

python scripts/container_smoke.py --image expense-agent:local

This needs only Python's standard library and Docker on the host (your activated .venv311 is fine). It creates random, disposable containers and volumes, binds no ports, disables networking, and uses temporary test keys. It verifies HTTP health, authentication, hidden Swagger, UID 10001, and SQLite/image/cache survival across container recreation. It removes only its own test resources afterward. The stored receipt is a synthetic failure fixture, not an LLM result.

The Docker build now builds the React frontend in a separate Node stage and copies only its static output into the Python runtime. Node and npm are absent from the final image. Open /ui/ for the receipt workspace, even with Swagger disabled; all receipt data and images still require the app key. See the frontend guide for development, review steps and private AWS access.

For a real workflow check, upload through /ui/ or /docs, copy the ID, run docker compose up -d --force-recreate api, and retrieve the same ID again. A real upload uses the normal paid extraction/classification calls. The first Paddle request downloads model weights and can be much slower than later requests.

Runtime checks and security

  • The process runs as UID/GID 10001 with all Linux capabilities dropped, no new privileges, a read-only root filesystem and a bounded temporary area.
  • The API is published only at 127.0.0.1; keep port 8000 closed in Lightsail's public firewall. Caddy proxies public HTTPS requests to authenticated API routes; use an SSH tunnel only for deliberate loopback maintenance.
  • One Uvicorn worker is used, with no development reload. Docker forwards signals through an init process and allows 330 seconds before forced shutdown; Uvicorn gets 300 seconds for graceful shutdown. Very long/hung Paddle inference can still be interrupted and leave a record PROCESSING.
  • Startup validates required configuration, OCR package/executable presence and writable receipt/database/cache storage. It does not download models or call the LLM. Paddle initialization failures return a controlled 503.
  • /health is a liveness check. It does not continuously verify the database, gateway connectivity or Paddle readiness. Docker health status alone does not automatically restart an unhealthy process; unless-stopped restarts exits.
  • Access logs are disabled to avoid logging receipt IDs in request URLs. Docker logs rotate at 10 MB with three files. Native OCR libraries may still emit diagnostics; inspect logs before sharing them.
  • Production is still one trusted workspace. Firebase protects browser requests; the shared key is reserved for controlled integrations. This is not a public multi-tenant authorization model. Do not mount the Docker socket.

Useful commands:

docker compose ps
docker compose logs --tail=100 api
docker stats --no-stream
docker compose stop api
docker compose start api

Lightsail deployment and subsequent updates

Provision Ubuntu x86-64, attach a static IP, install Docker Engine and Compose, and clone the public Ledgerly repository or use the existing checkout. Add .env on the server with restricted permissions (chmod 600 .env). Use the same Compose commands. The Python 3.11 interpreter is in the image; Ubuntu's host Python version does not need changing. Never copy a Windows .venv311 into the server or image.

For maintenance access, you can use your configured SSH key to open a private tunnel from Windows:

ssh -L 18000:127.0.0.1:8000 ubuntu@YOUR_STATIC_IP

Production API documentation is disabled. Use the tunnel only for deliberate maintenance with a temporary non-production configuration. Normal access is through Caddy at the configured HTTPS domain; see authentication and production deployment.

Before an update, back up data and preserve the old image under a unique tag. The Lightsail commands must include both Compose files. Starting the base file alone on a production host would omit the hybrid authentication and disabled API docs from the production overlay.

docker image tag expense-agent:local expense-agent:before-update-YYYYMMDD
git pull --ff-only origin main
docker compose -f compose.yaml -f compose.production.yaml build api
docker compose -f compose.yaml -f compose.production.yaml up -d --wait --wait-timeout 180

Replace the date placeholder with a unique tag. Run smoke checks after updating. For an application-only rollback with a compatible database schema, retag the saved image as expense-agent:local and recreate the API with the production overlay:

docker image tag expense-agent:before-update-YYYYMMDD expense-agent:local
docker compose -f compose.yaml -f compose.production.yaml up -d --no-build --force-recreate api

If a later release changes the schema, use that release's migration/restore procedure; an old image alone is not a safe database rollback.

Official references: Docker on Ubuntu, Compose services, Docker volumes.