Serve the SPA with Bun, drop nginx
Browse files at this commit4f9c8ec2818c24e82b5ca71bea963c7209fc334bParent: 7963aad- feat
- serve the SPA with Bun, drop nginx
4 changed files +157 -19
- Containerfile +14 -17
- compose.yaml +4 -1
- server.ts +138 -0
- vite.config.ts +1 -1
Containerfilemodified+14 -17
| @@ -1,3 +1,7 @@ | |||
| 1 | +# Build the SPA, then serve the static bundle with Bun (which also reverse- | ||
| 2 | +# proxies /api to the backend — see server.ts). No nginx: one runtime, one | ||
| 3 | +# tool, same-origin preserved. | ||
| 4 | + | ||
| 1 | FROM docker.io/oven/bun:1 AS build | 5 | FROM docker.io/oven/bun:1 AS build |
| 2 | WORKDIR /app | 6 | WORKDIR /app |
| 3 | COPY package.json bun.lock ./ | 7 | COPY package.json bun.lock ./ |
| @@ -6,24 +10,17 @@ RUN --mount=type=cache,target=/root/.bun/install/cache \ | |||
| 6 | COPY . . | 10 | COPY . . |
| 7 | RUN bun run build | 11 | RUN bun run build |
| 8 | 12 | ||
| 9 | -FROM docker.io/library/debian:trixie-slim AS serve | 13 | +FROM docker.io/oven/bun:1-slim AS serve |
| 10 | - | 14 | +WORKDIR /app |
| 11 | -RUN apt-get update && \ | 15 | +# Only the built assets and the server script are needed at runtime; server.ts |
| 12 | - apt-get install -y --no-install-recommends nginx curl ca-certificates && \ | 16 | +# imports nothing but Bun built-ins, so there are no node_modules to copy. |
| 13 | - rm -rf /var/lib/apt/lists/* && \ | 17 | +COPY --from=build /app/dist ./dist |
| 14 | - useradd --system --uid 10001 hezarfen && \ | 18 | +COPY server.ts ./server.ts |
| 15 | - mkdir -p /var/cache/nginx /var/lib/nginx /var/log/nginx && \ | ||
| 16 | - chown -R hezarfen:hezarfen /var/cache/nginx /var/lib/nginx /var/log/nginx /usr/share/nginx/html && \ | ||
| 17 | - rm -f /etc/nginx/sites-enabled/default | ||
| 18 | - | ||
| 19 | -COPY nginx.conf /etc/nginx/conf.d/default.conf | ||
| 20 | -COPY --from=build /app/dist /usr/share/nginx/html | ||
| 21 | -RUN sed -i 's|pid /run/nginx.pid;|pid /tmp/nginx.pid;|' /etc/nginx/nginx.conf | ||
| 22 | - | ||
| 23 | -USER hezarfen | ||
| 24 | 19 | ||
| 25 | ENV PORT=5173 | 20 | ENV PORT=5173 |
| 26 | - | ||
| 27 | EXPOSE 5173 | 21 | EXPOSE 5173 |
| 22 | +USER bun | ||
| 28 | 23 | ||
| 29 | -CMD ["nginx", "-g", "daemon off;"] | 24 | +# Healthcheck lives in compose.yaml (podman's OCI image format ignores a |
| 25 | +# Containerfile HEALTHCHECK). | ||
| 26 | +CMD ["bun", "run", "server.ts"] | ||
compose.yamlmodified+4 -1
| @@ -9,9 +9,12 @@ services: | |||
| 9 | - "5173:5173" | 9 | - "5173:5173" |
| 10 | environment: | 10 | environment: |
| 11 | PORT: "5173" | 11 | PORT: "5173" |
| 12 | + # Backend on the shared compose network; server.ts proxies /api here. | ||
| 13 | + BACKEND_ORIGIN: "http://hezarfen-backend:8080" | ||
| 12 | restart: unless-stopped | 14 | restart: unless-stopped |
| 13 | healthcheck: | 15 | healthcheck: |
| 14 | - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:5173/"] | 16 | + # Bun-based: the slim runtime image ships no curl. |
| 17 | + test: ["CMD", "bun", "-e", "fetch('http://127.0.0.1:5173/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] | ||
| 15 | interval: 30s | 18 | interval: 30s |
| 16 | timeout: 5s | 19 | timeout: 5s |
| 17 | retries: 3 | 20 | retries: 3 |
server.tsadded+138 -0
| @@ -0,0 +1,138 @@ | |||
| 1 | +// Production server: serve the built SPA and reverse-proxy /api/* to the | ||
| 2 | +// backend, so the browser stays same-origin (session cookies, no CORS). This | ||
| 3 | +// replaces the old nginx image — Bun serves the static `dist/` and bridges | ||
| 4 | +// both plain HTTP and the exam-room WebSocket through to the backend. | ||
| 5 | +// | ||
| 6 | +// Local dev uses Vite's own proxy (vite.config.ts); this file is only the | ||
| 7 | +// container's runtime after `vite build`. | ||
| 8 | + | ||
| 9 | +const PORT = Number(Bun.env.PORT ?? 5173); | ||
| 10 | +// Where the backend lives on the compose network. Override in compose. | ||
| 11 | +const BACKEND_ORIGIN = Bun.env.BACKEND_ORIGIN ?? "http://127.0.0.1:8080"; | ||
| 12 | +const BACKEND_HTTP = BACKEND_ORIGIN.replace(/\/+$/, ""); | ||
| 13 | +const BACKEND_WS = BACKEND_HTTP.replace(/^http/, "ws"); | ||
| 14 | +const BACKEND_HOST = new URL(BACKEND_HTTP).host; | ||
| 15 | + | ||
| 16 | +const DIST = `${import.meta.dir}/dist`; | ||
| 17 | + | ||
| 18 | +// Strip the /api prefix exactly like nginx did (rewrite ^/api(/.*)$ -> $1), | ||
| 19 | +// so /api/exams/x -> /exams/x and /api -> "". | ||
| 20 | +function backendPath(url: URL): string { | ||
| 21 | + return url.pathname.replace(/^\/api(?=\/|$)/, "") + url.search; | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +function isApi(pathname: string): boolean { | ||
| 25 | + return pathname === "/api" || pathname.startsWith("/api/"); | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +// One held-open client socket to the backend per browser socket. Frames are | ||
| 29 | +// piped both ways; messages that arrive before the upstream finishes its | ||
| 30 | +// handshake are queued, not dropped. | ||
| 31 | +type Bridge = { | ||
| 32 | + upstream: WebSocket; | ||
| 33 | + ready: boolean; | ||
| 34 | + queue: (string | Uint8Array)[]; | ||
| 35 | +}; | ||
| 36 | + | ||
| 37 | +async function serveStatic(pathname: string): Promise<Response> { | ||
| 38 | + // No path traversal out of dist. | ||
| 39 | + if (pathname.includes("..")) return new Response("bad request", { status: 400 }); | ||
| 40 | + const rel = pathname === "/" ? "/index.html" : pathname; | ||
| 41 | + const file = Bun.file(DIST + rel); | ||
| 42 | + if (await file.exists()) { | ||
| 43 | + const headers: Record<string, string> = {}; | ||
| 44 | + // Vite emits content-hashed files under /assets — safe to cache forever. | ||
| 45 | + if (rel.startsWith("/assets/")) headers["Cache-Control"] = "public, max-age=31536000, immutable"; | ||
| 46 | + else if (rel === "/index.html") headers["Cache-Control"] = "no-store"; | ||
| 47 | + return new Response(file, { headers }); | ||
| 48 | + } | ||
| 49 | + // SPA fallback: unknown paths are client routes, serve the shell. | ||
| 50 | + return new Response(Bun.file(`${DIST}/index.html`), { headers: { "Cache-Control": "no-store" } }); | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +async function proxyHttp(req: Request, url: URL): Promise<Response> { | ||
| 54 | + const target = BACKEND_HTTP + backendPath(url); | ||
| 55 | + const headers = new Headers(req.headers); | ||
| 56 | + // Let fetch set Host from the target; forwarding the browser's Host confuses | ||
| 57 | + // the backend's absolute-URL / cookie-domain logic. | ||
| 58 | + headers.set("host", BACKEND_HOST); | ||
| 59 | + const hasBody = req.method !== "GET" && req.method !== "HEAD"; | ||
| 60 | + const resp = await fetch(target, { | ||
| 61 | + method: req.method, | ||
| 62 | + headers, | ||
| 63 | + body: hasBody ? req.body : undefined, | ||
| 64 | + redirect: "manual", | ||
| 65 | + // Stream the request body instead of buffering it (uploads). | ||
| 66 | + ...(hasBody ? { duplex: "half" } : {}), | ||
| 67 | + } as RequestInit); | ||
| 68 | + return resp; | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +const server = Bun.serve<Bridge, {}>({ | ||
| 72 | + port: PORT, | ||
| 73 | + hostname: "0.0.0.0", | ||
| 74 | + // Long-running exam sockets must not be reaped by an idle timeout; the | ||
| 75 | + // backend sends its own periodic state ticks but a quiet client can still | ||
| 76 | + // sit for minutes between frames. | ||
| 77 | + idleTimeout: 0, | ||
| 78 | + async fetch(req, srv) { | ||
| 79 | + const url = new URL(req.url); | ||
| 80 | + | ||
| 81 | + if (isApi(url.pathname)) { | ||
| 82 | + // WebSocket upgrade (/api/exams/:id/attempt/ws): open the upstream and | ||
| 83 | + // bridge. Forward the session cookie — it's what authenticates the WS. | ||
| 84 | + if (req.headers.get("upgrade")?.toLowerCase() === "websocket") { | ||
| 85 | + const cookie = req.headers.get("cookie") ?? undefined; | ||
| 86 | + const proto = req.headers.get("sec-websocket-protocol") ?? undefined; | ||
| 87 | + const upstream = new WebSocket(BACKEND_WS + backendPath(url), { | ||
| 88 | + headers: cookie ? { cookie } : undefined, | ||
| 89 | + ...(proto ? { protocols: proto.split(",").map((p) => p.trim()) } : {}), | ||
| 90 | + } as unknown as string[]); | ||
| 91 | + const bridge: Bridge = { upstream, ready: false, queue: [] }; | ||
| 92 | + const ok = srv.upgrade(req, { data: bridge }); | ||
| 93 | + if (ok) return undefined; | ||
| 94 | + upstream.close(); | ||
| 95 | + return new Response("websocket upgrade failed", { status: 426 }); | ||
| 96 | + } | ||
| 97 | + return proxyHttp(req, url); | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + return serveStatic(url.pathname); | ||
| 101 | + }, | ||
| 102 | + websocket: { | ||
| 103 | + open(ws) { | ||
| 104 | + const b = ws.data; | ||
| 105 | + b.upstream.onopen = () => { | ||
| 106 | + b.ready = true; | ||
| 107 | + for (const m of b.queue) b.upstream.send(m); | ||
| 108 | + b.queue.length = 0; | ||
| 109 | + }; | ||
| 110 | + b.upstream.onmessage = (e) => { | ||
| 111 | + // e.data is string for text frames, ArrayBuffer/Uint8Array for binary. | ||
| 112 | + ws.send(e.data as string | Uint8Array); | ||
| 113 | + }; | ||
| 114 | + b.upstream.onclose = (e) => ws.close(e.code || 1000, e.reason); | ||
| 115 | + b.upstream.onerror = () => { | ||
| 116 | + try { | ||
| 117 | + ws.close(1011, "upstream error"); | ||
| 118 | + } catch { | ||
| 119 | + // socket already gone | ||
| 120 | + } | ||
| 121 | + }; | ||
| 122 | + }, | ||
| 123 | + message(ws, message) { | ||
| 124 | + const b = ws.data; | ||
| 125 | + if (b.ready) b.upstream.send(message); | ||
| 126 | + else b.queue.push(message); | ||
| 127 | + }, | ||
| 128 | + close(ws, code, reason) { | ||
| 129 | + try { | ||
| 130 | + ws.data.upstream.close(code >= 1000 && code <= 4999 ? code : 1000, reason); | ||
| 131 | + } catch { | ||
| 132 | + // upstream already closed | ||
| 133 | + } | ||
| 134 | + }, | ||
| 135 | + }, | ||
| 136 | +}); | ||
| 137 | + | ||
| 138 | +console.log(`serving dist/ on :${server.port}, proxying /api -> ${BACKEND_HTTP}`); | ||
vite.config.tsmodified+1 -1
| @@ -18,7 +18,7 @@ export default defineConfig({ | |||
| 18 | // reloads its cache entries wedge and every later request queues in the | 18 | // reloads its cache entries wedge and every later request queues in the |
| 19 | // browser forever — no bytes ever reach vite. `no-store` stops Chromium | 19 | // browser forever — no bytes ever reach vite. `no-store` stops Chromium |
| 20 | // from creating the cache entries at all. Dev-only; the production build | 20 | // from creating the cache entries at all. Dev-only; the production build |
| 21 | - // is served by nginx with its own cache headers. | 21 | + // is served by Bun (server.ts) with its own cache headers. |
| 22 | headers: { | 22 | headers: { |
| 23 | "Cache-Control": "no-store", | 23 | "Cache-Control": "no-store", |
| 24 | }, | 24 | }, |