# Building an app on a MicroServer — playbook for AI assistants > **For the person:** fill in the values in section 0, then give this file to your AI assistant > (Claude Code: save it as `CLAUDE.md` in the app's repository or paste it at the start of the chat; > other tools: `AGENTS.md`, project rules or system prompt). > Every address and account below is an **example**. Replace them with your own. > **Never put passwords, Cloudflare tokens or API keys in this file.** > > Source: https://www.hongeuichan.com/microhomeserver/ai.html --- You are helping a developer build an app (mobile or web) whose backend runs on their **MicroServer**: a small ARM64 board at home (ODROID-M1S or similar, Ubuntu, MicroServer package) that reaches the internet only through **Cloudflare Tunnel**. This file tells you how to reach the server, what you may do there by yourself, how the app's database is created and changed, and where server information is kept so every session (and every developer) sees the same facts. ## 0. Values for this server | Placeholder | Meaning | Example (replace) | |---|---|---| | `` | SSH name on the developer's computer | `microserver` | | `` | tunnel hostname for SSH | `ssh-home.example.com` | | `` | SSH port on the board | `22` | | `` | login account on the board (has sudo) | `odroid` | | `` | private key on the developer's computer | `~/.ssh/microserver_ed25519` | | `` | board address at home (optional shortcut) | `192.168.1.50` | | `` | tunnel hostname shared by all app APIs | `api.example.com` | | `` | where app backends live on the board | `/home/apps` | | `` | big disk (SSD) for backups and large data | `/data` | | `` | this app's short name (lowercase) | `myapp` | | `` | this app's port, from the registry (9100–9199) | `9101` | ## 1. The picture ``` Phone / web app ──HTTPS──▶ https:////... │ Cloudflare (certificate, DDoS shield) ▼ tunnel (outbound from the board, no router ports) Board: Apache :80 ──path //──▶ 127.0.0.1: -api container │ private Docker network ▼ -db container (no port) Developer + AI ──SSH over the tunnel (cloudflared)──▶ board : deploy, database work, logs Owner ──▶ Cloudflare dashboard (hostnames, access rules), MicroServer dashboard (http://:8800, home only), secrets ``` Three rules hold everything together: 1. **Clients talk only to the API**, over HTTPS. Never to the database. 2. **The database has no published port.** Only its own API container reaches it. 3. **Every app service binds to `127.0.0.1`.** The only way in from outside is the tunnel. ## 2. Connecting the server to Cloudflare (owner, once) 1. Cloudflare **Zero Trust → Networks → Tunnels**: create a *Cloudflared* tunnel, paste its token into the MicroServer dashboard's **Cloudflare Tunnel** card. 2. In the tunnel's **Public Hostname** tab add: | Hostname | Service | Used for | |---|---|---| | `` | **HTTP** `localhost:80` | all app APIs, split by path (`//`) | | `` | **SSH** `localhost:` | developers and AI reaching the board from anywhere | 3. Protect SSH: tunnel SSH reaches the board from 127.0.0.1, so fail2ban cannot block it. Turn on **key-only login** (section 3) and, ideally, a Cloudflare Access policy on ``. If an AI must connect unattended through Access, the owner creates an Access **service token** for it instead of a browser login. One API hostname shared by path means a new app needs **no Cloudflare change**, only one Apache line. ## 3. Giving the AI access to the board (developer + owner, once per computer) On the developer's computer: ```bash brew install cloudflared # macOS; Linux/Windows: Cloudflare's packages ssh-keygen -t ed25519 -f -C "-microserver" ``` The owner adds `.pub` to `~/.ssh/authorized_keys` of `` on the board (at home: `ssh-copy-id -i .pub -p @`). `~/.ssh/config`: ``` Host HostName ProxyCommand cloudflared access ssh --hostname %h Port User IdentityFile IdentitiesOnly yes HostKeyAlias ``` (Use the full path of `cloudflared`, e.g. `/opt/homebrew/bin/cloudflared`, if `ssh` can't find it. At home you may add a second host with `HostName ` and no `ProxyCommand`, keeping the same `HostKeyAlias` so both routes check the same host key.) Check, then you are ready: ```bash ssh 'hostname; uptime; sudo -n true && echo sudo-ok' ``` How you (the AI) work on the board: - Run commands as `ssh ''`, copy files with `rsync -az ... :`. No interactive editors or prompts; use `sudo -n`. - If `sudo -n` fails, the owner decides: allow passwordless sudo for ``, or run those steps. - If the host key ever changes, **stop and tell the owner**. - Key-only login (owner's OK, after the key works) — `/etc/ssh/sshd_config.d/10-key-only.conf`: `PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin no`, then `sudo sshd -t && sudo systemctl reload ssh`, keeping one session open while testing. ## 4. What you may do on the board | You do it yourself | Ask the owner first | Never | |---|---|---| | Read status, logs, `docker ps`, disk space | Reboot or shut down the board | Type, print or store secrets in chat, git or logs | | Create and update `//` | Restart the Docker or Apache service, or cloudflared | Publish a database port or port 8800 | | Build, start, stop **this app's** containers | Anything that deletes data (`rm -rf`, `docker volume rm`, `DROP`, `TRUNCATE`) | Bind an app port without `127.0.0.1` | | Apply additive DB migrations, run backups | Destructive or data-rewriting migrations | Write the home's public IP anywhere | | Add this app's Apache path, `configtest`, `reload` | Cloudflare changes (the owner does them) | Touch MicroServer files (`/opt/microserver`, `/var/lib/microserver`, `microserver-*.conf`) | | Add this app's backup cron job | Other apps' folders, containers or databases | Use end-of-life software versions | | Update the registry and `docs/server.md` | Firewall (`ufw`), SSH settings, system packages | Open router or `ufw` ports | After any change on the board, say what you changed in one or two lines. ## 5. App development workflow ### Step 1 — Reserve a name, port and path Read the registry on the board, pick the next free port, add a line **before** deploying: ```bash ssh 'cat /REGISTRY.md; sudo ss -ltnp | grep 127.0.0.1:91' ``` `/REGISTRY.md` (create it if missing): ``` | App | Folder | Port | Public path | Repository | Since | |---|---|---|---|---|---| | myapp | /home/apps/myapp | 9101 | https://api.example.com/myapp/ | github.com/you/myapp | 2026-01-01 | ``` ### Step 2 — Repository layout ``` / app/ client (Android, iOS, web) server/ compose.yml api/ API code + Dockerfile (linux/arm64) db/init/001_schema.sql first-time schema db/migrations/ 002_add_x.sql, 003_... (numbered, never edited after use) deploy/.conf the Apache path lines .env.example variable names only, no values docs/ server.md server handoff file (section 6) api.md API contract (section 6) ``` ### Step 3 — compose.yml (API + its own database) ```yaml services: api: build: ./api container_name: -api restart: unless-stopped ports: - "127.0.0.1::8080" # ALWAYS 127.0.0.1 env_file: .env # DB_HOST=db, DB_NAME, DB_USER, DB_PASSWORD, ... depends_on: db: { condition: service_healthy } db: image: mariadb: # or postgres: container_name: -db restart: unless-stopped environment: MARIADB_DATABASE: MARIADB_USER: MARIADB_PASSWORD: ${DB_PASSWORD} MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD} volumes: - ./data/db:/var/lib/mysql - ./db/init:/docker-entrypoint-initdb.d:ro healthcheck: test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] interval: 10s retries: 10 # no "ports:" — only the api container reaches the database (host name "db") ``` > ⚠️ `ports: "9101:8080"` without `127.0.0.1:` makes Docker bypass the firewall and expose the > port to every network. The board is ARM64: images must support `linux/arm64`. Build on the board (fine for small images) or on the developer's computer with `docker buildx build --platform linux/arm64` and send it with `docker save | gzip | ssh 'gunzip | sudo docker load'`. ### Step 4 — Secrets are born on the board Create `.env` **on the board** with random values; they never travel to the developer's computer or the chat: ```bash ssh 'cd / && umask 077 && [ ! -f .env ] && cp .env.example .env && \ sed -i -e "s/^DB_PASSWORD=.*/DB_PASSWORD=$(openssl rand -hex 24)/" \ -e "s/^DB_ROOT_PASSWORD=.*/DB_ROOT_PASSWORD=$(openssl rand -hex 24)/" .env' ``` Secrets the owner brings (push-notification keys, store keys, third-party API keys): the owner copies the file straight to the board, e.g. into `//secrets/` (`chmod 600`), and the container mounts it read-only. You refer to it only by path or variable name. DB passwords are used **only when the database is first created** (empty `data/db`). Changing `.env` later does not change them. ### Step 5 — Deploy ```bash # from the repository ssh 'sudo mkdir -p / && sudo chown $USER: /' rsync -az --exclude .env --exclude data --exclude secrets server/ :// ssh 'cd / && sudo docker compose up -d --build --pull always \ && curl -fsS http://127.0.0.1:/health' ``` Re-deploying after code changes is the same `rsync` + `docker compose up -d --build` (`.env`, `data/` and `secrets/` stay untouched). ### Step 6 — Route the path Add to the Apache virtual host that serves `` (create it once if it doesn't exist): ```apache ServerName ProxyPreserveHost On # one pair of lines per app ProxyPass // http://127.0.0.1:/ ProxyPassReverse // http://127.0.0.1:/ ErrorLog ${APACHE_LOG_DIR}/api-error.log CustomLog ${APACHE_LOG_DIR}/api-access.log combined ``` ```bash ssh 'sudo apache2ctl configtest && sudo systemctl reload apache2 && \ curl -fsS -H "Host: " http://127.0.0.1//health' curl -fsS https:////health ``` - Keep `access` in the access-log name: MicroServer's attack defense reads `*access*.log` and blocks attackers for apps behind Apache automatically. - First time only: `sudo a2enmod proxy proxy_http headers` (`proxy_wstunnel` for WebSocket). If Apache isn't installed: `sudo apt install apache2` then `sudo dpkg-reconfigure microserver` (adds the real-visitor-IP setting) — ask the owner first. - The app sees the real visitor IP in the `CF-Connecting-IP` header. ### Step 7 — Point the client at the server - Base URL in build config, not in code: release → `https:////`, debug → the same or a local server. - No secrets in the client. The API issues each user/device its own token; the client stores it in the platform's secure storage. - Version every endpoint or the payload (`/v1/...`) so old app versions keep working. ### Step 8 — Show the app on the dashboard (server 0.1.13+) The dashboard's "App services" card and the phone app show, per app, traffic from the Apache log (visitors, requests, response time, server errors) and, if the app answers a stats address, its own counts (users, sign-ups, active users and up to 8 numbers of its own). 1. Add a stats endpoint to the API. It answers **counts only**, never personal data: ```json {"users_total": 1234, "signups_today": 5, "active_24h": 210, "active_now": 12, "extra": [{"label": {"en": "Orders today", "ko": "오늘 주문"}, "value": 88}]} ``` Every field is optional. It must answer only when the `X-MicroServer-Key` header matches the key in `.env` (compare in constant time), and must refuse (404) any request that has `X-Forwarded-For` — the same port is reachable from the internet through Apache. Example path: `/_microserver/stats.php`. For "active", keep a `last_seen_at` per user/device and update it at most once a minute. 2. Make the key on the board, never on your computer, and put it in the app's `.env` (e.g. `_STATS_KEY=$(openssl rand -hex 24)`). 3. Register the app (root owns the file, group `microserver` reads it): ```bash # /etc/microserver/services.d/.json { "name": "", "hosts": [""], "paths": ["//"], "containers": ["-api", "-db"], "stats_url": "http://127.0.0.1:/_microserver/stats.php", "stats_key": "" } sudo install -m 0640 -o root -g microserver .json /etc/microserver/services.d/.json sudo /opt/microserver/bin/webstats check # shows what it understood and the app's answer ``` `stats_url` and `stats_key` can be left out: the card then shows traffic only. Numbers appear within a minute. Recreate only the API container after adding the key: `sudo docker compose up -d --no-deps `. ## 6. Exchanging server information Keep each kind of information in exactly one place: | What | Where | Who reads it | |---|---|---| | Non-secret facts about this app on the server | `docs/server.md` in the app repository | every AI session and developer, at the start of work | | Which ports and paths are taken on the board | `/REGISTRY.md` on the board | anyone adding an app | | Secrets | `//.env` and `secrets/` on the board only | the containers | | Variable names (no values) | `server/.env.example` in the repository | developers, AI | | API endpoints, requests, responses, errors | `docs/api.md` (or OpenAPI) in the repository | client and server work alike | Rules: - **Read `docs/server.md` before touching the server; update it right after.** That file is how the next session (or another developer's AI) learns what you did. - Change the **API contract first** (`docs/api.md`), then server and client. - Never put passwords, tokens or the home's public IP in any of these files. `docs/server.md` template: ```markdown # on the MicroServer - SSH: `ssh ` (key + Cloudflare Tunnel, see CLAUDE.md) - Folder: / · containers: -api, -db - Port: 127.0.0.1: · public: https://// - Health: https:////health - Database: MariaDB , db/user ``, data in //data/db - Applied migrations: 001_schema, 002_add_x (latest first in the list below) - Backups: /backup// daily 03:30, kept 14 days - Deploy: rsync server/ → `sudo docker compose up -d --build` - Secrets on the board (names only): DB_PASSWORD, DB_ROOT_PASSWORD, PUSH_KEY_FILE - Log: 2026-01-01 first deploy · 2026-01-05 migration 002 ``` ## 7. Database: how it is created and changed **First creation.** When `data/db` is empty, the database container creates the database and user from the environment and runs everything in `db/init/` once. **Changes (migrations).** 1. Write a new numbered file in `db/migrations/` (`003_add_orders.sql`). Never edit an applied one. 2. Prefer additive changes (new tables/columns, nullable or with defaults) so the running app keeps working. 3. Back up, then apply: ```bash ssh 'sudo mkdir -p /backup/ && sudo chown $USER: /backup/' ssh 'cd / && sudo docker compose exec -T db sh -c \ "mariadb-dump -uroot -p\"\$MARIADB_ROOT_PASSWORD\" \"\$MARIADB_DATABASE\"" \ | gzip > /backup//before-003.sql.gz' ssh 'cd / && sudo docker compose exec -T db sh -c \ "mariadb -uroot -p\"\$MARIADB_ROOT_PASSWORD\" \"\$MARIADB_DATABASE\"" \ < db/migrations/003_add_orders.sql' ``` 4. Record it in `docs/server.md` (applied migrations). 5. Dropping or rewriting data → **ask the owner first**. If the API framework has its own migration tool (Alembic, Prisma Migrate, Flyway, Laravel, golang-migrate…), use it instead, run as `sudo docker compose run --rm api `. **Looking at data.** Read-only queries through the container: `sudo docker compose exec db sh -c 'mariadb -u"$MARIADB_USER" -p"$MARIADB_PASSWORD" "$MARIADB_DATABASE" -e "SELECT ..."'`. Never copy personal data off the board for convenience. **Backups.** MicroServer does not back up app data. Add a daily dump (as root, `/etc/cron.d/-backup`): ``` 30 3 * * * root cd / && docker compose exec -T db sh -c 'mariadb-dump -uroot -p"$MARIADB_ROOT_PASSWORD" "$MARIADB_DATABASE"' | gzip > /backup//$(date +\%F).sql.gz && find /backup/ -name '*.sql.gz' -mtime +14 -delete ``` Restore = stop the api, pipe the dump into `mariadb` the same way, start the api (owner's OK). **Local development.** The same `server/compose.yml` runs on the developer's computer (`docker compose up`) with a local `.env`; never point a local app at the production database. ## 8. Limits - The tunnel carries **HTTP, HTTPS and WebSocket only**. Raw TCP/UDP (game relays, etc.) need another server. - ~4 GB RAM and a slow CPU shared by every app: keep images small, avoid heavy builds on the board. - The board is in someone's home: power or internet can drop. Use `restart: unless-stopped`, make clients retry, keep backups. ## 9. Troubleshooting ```bash ssh 'cd / && sudo docker compose ps && sudo docker compose logs --tail=100' ssh 'sudo tail -n 50 /var/log/apache2/api-error.log' ssh 'sudo journalctl -u cloudflared --since "10 min ago"' ssh 'curl -s 127.0.0.1:20241/config' # tunnel's public hostnames ssh 'sudo ipset list ms-block' # IPs blocked by the attack defense ssh 'sudo /opt/microserver/bin/defense unban ' ``` - **502**: the tunnel service is `https://` instead of `http://`, or the container is down. - **Default page instead of the API**: `ServerName` doesn't match ``. - **Your IP gets blocked**: probing many odd paths looks like a scan (blocked 6 h). Home IPs are never blocked. - **SSH hangs**: `cloudflared` missing or not on the path, or the tunnel is down (the owner can check the MicroServer dashboard at home).