feat(deploy): Docker images for server (API+SPA) and vision + branch-aware build pipeline
Containerize the two non-desktop apps for the booth appliance. The desktop app stays on its own tag-only release.yml. - apps/server/Dockerfile: multi-stage node:22-alpine. `pnpm deploy --legacy --prod` (NOT prune — the monorepo native better-sqlite3 won't resolve under a root prune) yields a self-contained bundle; build stage adds node-gyp toolchain, runtime adds libstdc++; non-root, healthcheck. Migrates the mounted DB on boot via a drizzle-kit- free runtime migrator (packages/db/scripts/migrate-runtime.mjs) — drizzle-kit is a devDep, pruned from prod. - apps/server/src/static-spa.ts: Fastify serves the built React SPA (one container serves API + UI). GET-only fallback to index.html, excludes /api + /health so it never shadows the backend; a no-op in dev (no dist). Registered last in server.ts. - apps/vision/Dockerfile: uv base, --extra alpr, model weights PRE-WARMED into the image as the runtime user so fast_alpr boots offline (0 downloads at runtime). Engine env- selected (VISION_RECOGNIZER stub|fast_alpr). - Branch-aware: docker-compose.yml (base) + .dev.yml (build local, stub, ports) + .prod.yml (pull pinned, fast_alpr, vision internal, restart always); REGISTRY/TAG from env so a branch deploy pulls that branch's image. - .gitea/workflows/build-images.yml: on push to dev/main, run the full turbo build+lint+ test gate, then buildx push both images to git.infra.msai.al/mca/parking_solution with branch + branch-<sha> tags (registry cache; optional Komodo webhook behind KOMODO_ENABLED). - .dockerignore excludes **/parking.sqlite* so the signed ledger is NEVER baked. Verified locally (Docker 29): server image migrates + serves API+SPA (/health 200, / + /booth HTML, /api/nope JSON 404, no sqlite outside /data); vision image boots fast_alpr with 0 runtime downloads; compose stack healthy with server→vision over the private network. Wiki: new container-deployment.md; vision-service-packaging open Qs resolved; index + log. Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Parking SERVER image: Fastify API + the bundled React SPA (one container serves both —
|
||||
# offline-first single appliance). Build CONTEXT is the REPO ROOT (it's a pnpm/turbo
|
||||
# monorepo). better-sqlite3 is a native module → build stage needs node-gyp toolchain,
|
||||
# runtime needs libstdc++. Mirrors the house multi-stage pattern (cf. trm/processor).
|
||||
# See wiki/decisions/container-deployment.md.
|
||||
|
||||
# ---- deps: cache-friendly pnpm fetch (only manifests change the layer) ----
|
||||
FROM node:22-alpine AS deps
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache python3 make g++ # node-gyp for better-sqlite3
|
||||
RUN corepack enable && corepack prepare pnpm@10.24.0 --activate
|
||||
# Workspace manifests + lock first, so the fetch layer caches across source edits.
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./
|
||||
COPY apps/server/package.json apps/server/
|
||||
COPY apps/web/package.json apps/web/
|
||||
COPY apps/vision/package.json apps/vision/
|
||||
COPY packages/db/package.json packages/db/
|
||||
COPY packages/devices/package.json packages/devices/
|
||||
COPY packages/shared/package.json packages/shared/
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||
pnpm fetch
|
||||
|
||||
# ---- build: install (offline from the fetched store) + turbo build everything ----
|
||||
FROM deps AS build
|
||||
ENV CI=true
|
||||
COPY . .
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||
pnpm install --frozen-lockfile --offline
|
||||
# Builds shared/db/devices, the server dist, AND the web SPA dist (apps/web/dist).
|
||||
RUN pnpm turbo run build --filter=@parking/server --filter=@parking/web
|
||||
# `pnpm deploy` produces a SELF-CONTAINED prod bundle for the server in /deploy: a hoisted
|
||||
# node_modules with only @parking/server's prod deps (incl. the workspace packages' built
|
||||
# dist + their native deps like better-sqlite3 — properly linked, unlike `prune` at root).
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||
pnpm --filter=@parking/server --legacy deploy --prod /deploy
|
||||
# The server's own dist + scripts (deploy copies the package's package.json + files, but we
|
||||
# copy dist explicitly so the layout under /deploy is predictable). The web SPA + db
|
||||
# migrations are copied in the runtime stage from their build locations.
|
||||
|
||||
# ---- runtime: slim, non-root ----
|
||||
FROM node:22-alpine AS runtime
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
RUN apk add --no-cache libstdc++ # better-sqlite3 native runtime
|
||||
RUN addgroup -S app && adduser -S -G app app
|
||||
|
||||
# The self-contained deploy bundle: dist/ + a hoisted node_modules carrying the server's
|
||||
# prod deps AND the workspace packages (@parking/db|devices|shared) with their built dist,
|
||||
# the drizzle migrations, and the native better-sqlite3 binding. Single COPY — no scattered
|
||||
# package dirs, no root node_modules.
|
||||
COPY --from=build --chown=app:app /deploy ./
|
||||
|
||||
# The built SPA — served by Fastify static at WEB_DIST_DIR. (Not part of the server's deploy
|
||||
# bundle, so copied from the web build output.)
|
||||
COPY --from=build --chown=app:app /app/apps/web/dist ./web/dist
|
||||
|
||||
# DB lives on a mounted volume (never in the image). Default points at /data.
|
||||
ENV DATABASE_URL=/data/parking.sqlite
|
||||
ENV WEB_DIST_DIR=/app/web/dist
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=3000
|
||||
RUN mkdir -p /data && chown app:app /data
|
||||
VOLUME ["/data"]
|
||||
|
||||
USER app
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD wget -qO- "http://localhost:${PORT:-3000}/health" >/dev/null 2>&1 || exit 1
|
||||
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
CMD ["node", "dist/index.js"]
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Container entrypoint for the parking server. Applies DB migrations against the mounted
|
||||
# volume (DATABASE_URL), optionally seeds the first admin, then execs the server. Idempotent:
|
||||
# the runtime migrator (drizzle-orm migrator, no drizzle-kit) only applies pending migrations,
|
||||
# so a restart is a no-op. See packages/db/scripts/migrate-runtime.mjs.
|
||||
set -e
|
||||
|
||||
echo "[entrypoint] DATABASE_URL=${DATABASE_URL}"
|
||||
|
||||
# Apply migrations against the mounted DB file (creates it + the schema on first boot).
|
||||
# The migrator ships inside the @parking/db package in the deploy bundle's node_modules.
|
||||
node node_modules/@parking/db/scripts/migrate-runtime.mjs
|
||||
|
||||
# Optional first-boot admin seed: set SEED_ADMIN=1 plus ADMIN_USER + ADMIN_PASS (the seed
|
||||
# script PROMPTS when these are unset, which would hang a container — so require ADMIN_PASS).
|
||||
# The seed is idempotent: it won't overwrite an existing user unless FORCE=1.
|
||||
if [ "${SEED_ADMIN}" = "1" ]; then
|
||||
if [ -z "${ADMIN_PASS}" ]; then
|
||||
echo "[entrypoint] SEED_ADMIN=1 but ADMIN_PASS is unset — skipping seed (would hang on prompt)"
|
||||
else
|
||||
echo "[entrypoint] seeding admin (${ADMIN_USER:-admin})"
|
||||
node scripts/seed-admin.mjs || echo "[entrypoint] seed-admin skipped/failed (non-fatal)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "[entrypoint] starting server"
|
||||
exec "$@"
|
||||
@@ -44,6 +44,7 @@ import { printerRoutes } from "./routes/printers.js";
|
||||
import { setupRoutes } from "./routes/setup.js";
|
||||
import { deviceStatusRoutes } from "./routes/device-status.js";
|
||||
import { wsRoutes } from "./routes/ws.js";
|
||||
import { registerSpa } from "./static-spa.js";
|
||||
|
||||
// The backend is Fastify (Node). Hardware drivers live as isolated Fastify
|
||||
// plugins emitting onto a shared internal event bus; auth is fully local
|
||||
@@ -300,5 +301,12 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
});
|
||||
app.addHook("onClose", async () => unsubscribeInput());
|
||||
|
||||
// LAST: serve the built React SPA (apps/web/dist) when present — so one container
|
||||
// serves the API + the operator UI (offline-first single appliance). No-op in dev (no
|
||||
// build → the Vite dev server serves the UI). Registered after every API route and
|
||||
// GET-only with /api + /health excluded, so it can never shadow the backend.
|
||||
// See static-spa.ts + wiki/decisions/container-deployment.md.
|
||||
await registerSpa(app);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
// Serve the built React SPA (apps/web/dist) from the Fastify server, so ONE container
|
||||
// serves both the API and the operator UI — matching the offline-first single-appliance
|
||||
// model (the booth has no separate web host). This is a NO-OP in dev (the Vite dev server
|
||||
// serves the SPA on its own port and no dist exists), so it never changes local behavior.
|
||||
//
|
||||
// Registration order matters: this is registered LAST, after every API route, and its
|
||||
// catch-all is GET-only and explicitly excludes /api, /health, and the WS path — so it
|
||||
// can never shadow the backend. See wiki/decisions/container-deployment.md.
|
||||
|
||||
/** Where the built SPA lives. Override with WEB_DIST_DIR (the container sets it). Default
|
||||
* resolves relative to this file's dist location: apps/server/dist → ../../web/dist, the
|
||||
* layout the image lays down (/app/dist + /app/web/dist → ../web/dist from dist). */
|
||||
function resolveWebDist(): string {
|
||||
const fromEnv = process.env.WEB_DIST_DIR;
|
||||
if (fromEnv) return resolve(fromEnv);
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
// In the image the server runs from /app/dist and the SPA sits at /app/web/dist.
|
||||
return resolve(here, "../web/dist");
|
||||
}
|
||||
|
||||
/**
|
||||
* Register SPA static serving if a build is present. Returns true when wired, false when
|
||||
* skipped (dev / no build). Serves assets from the dist dir and falls back to index.html
|
||||
* for any non-API GET so client-side routing (TanStack Router) works on deep links/reload.
|
||||
*/
|
||||
export async function registerSpa(app: FastifyInstance): Promise<boolean> {
|
||||
const root = resolveWebDist();
|
||||
const indexHtml = resolve(root, "index.html");
|
||||
if (!existsSync(indexHtml)) {
|
||||
app.log.info(`SPA static serving disabled (no build at ${root})`);
|
||||
return false;
|
||||
}
|
||||
|
||||
await app.register(fastifyStatic, { root, wildcard: false });
|
||||
|
||||
// SPA fallback: any GET that didn't match an API route or a real static file returns
|
||||
// index.html (client routing). EXCLUDE the backend surfaces so a missing /api route
|
||||
// still 404s as JSON rather than silently returning the HTML shell. WS upgrades and
|
||||
// non-GET methods are never touched (this is a GET-only notFound handler path).
|
||||
app.setNotFoundHandler((req, reply) => {
|
||||
const url = req.raw.url ?? "/";
|
||||
if (req.method !== "GET" || url.startsWith("/api") || url.startsWith("/health")) {
|
||||
return reply.code(404).send({ error: "not found" });
|
||||
}
|
||||
return reply.sendFile("index.html");
|
||||
});
|
||||
|
||||
app.log.info(`SPA static serving enabled from ${root}`);
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user