Dockerfile 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # Build frontend
  2. FROM node:22-bookworm-slim AS frontend-builder
  3. WORKDIR /app/frontend
  4. # Copy package files first for better caching
  5. COPY frontend/package*.json ./
  6. # Use cache mount for npm
  7. RUN --mount=type=cache,target=/root/.npm \
  8. npm ci
  9. COPY frontend/ ./
  10. RUN npm run build
  11. # Production image
  12. FROM python:3.13-slim-trixie
  13. WORKDIR /app
  14. # Install system dependencies
  15. ENV DEBIAN_FRONTEND=noninteractive
  16. RUN apt-get update && apt-get install -y --no-install-recommends \
  17. curl \
  18. ffmpeg \
  19. gnupg \
  20. gosu \
  21. iproute2 \
  22. libcap2-bin \
  23. openssh-client \
  24. ca-certificates \
  25. && rm -rf /var/lib/apt/lists/*
  26. # Install the Tailscale CLI only (no tailscaled — the daemon runs on the host).
  27. # Bambuddy calls `tailscale status` / `tailscale cert` via the host's socket,
  28. # which the user mounts in via docker-compose when they want to enable the
  29. # Tailscale integration for virtual printers. Without the socket mount, the
  30. # binary is harmless — the code logs a hint and falls back to self-signed.
  31. #
  32. # The Tailscale package server occasionally returns 504; since the CLI is
  33. # optional (the code falls back to self-signed without it), a fetch failure must
  34. # not fail the whole image build. Retry a few times for transient blips, and on
  35. # sustained failure continue building without the CLI (cleaning up the partial
  36. # apt source so later `apt-get update` layers stay valid) rather than aborting.
  37. RUN set -eux; \
  38. if curl -fsSL --retry 5 --retry-connrefused --retry-delay 3 \
  39. https://pkgs.tailscale.com/stable/debian/trixie.noarmor.gpg \
  40. -o /usr/share/keyrings/tailscale-archive-keyring.gpg \
  41. && curl -fsSL --retry 5 --retry-connrefused --retry-delay 3 \
  42. https://pkgs.tailscale.com/stable/debian/trixie.tailscale-keyring.list \
  43. -o /etc/apt/sources.list.d/tailscale.list \
  44. && apt-get update \
  45. && apt-get install -y --no-install-recommends tailscale; then \
  46. echo "Tailscale CLI installed."; \
  47. else \
  48. echo "WARNING: Tailscale package server unavailable; building without the Tailscale CLI (optional integration)."; \
  49. rm -f /etc/apt/sources.list.d/tailscale.list /usr/share/keyrings/tailscale-archive-keyring.gpg; \
  50. fi; \
  51. rm -rf /var/lib/apt/lists/*
  52. # Allow binding to privileged ports (e.g. 990/FTPS) as non-root user.
  53. # File capabilities are more reliable than Docker cap_add with user: directive,
  54. # which depends on ambient capability support in the container runtime.
  55. RUN setcap cap_net_bind_service=+ep "$(readlink -f /usr/local/bin/python3)"
  56. # Install Python dependencies with cache mount.
  57. # pip is upgraded to >=26.1 first to close CVE-2026-6357 — the python:3.13-slim
  58. # base image ships pip 26.0.1, which runs its self-update check after installing
  59. # wheels (so a hostile wheel could hijack stdlib imports during install).
  60. COPY requirements.txt ./
  61. RUN --mount=type=cache,target=/root/.cache/pip \
  62. pip install --root-user-action=ignore --upgrade 'pip>=26.1' \
  63. && pip install --root-user-action=ignore -r requirements.txt
  64. # Copy backend
  65. COPY backend/ ./backend/
  66. # Capture the current git branch at build time. `.git/HEAD` is the only
  67. # .git metadata the build context lets through (see .dockerignore); it
  68. # contains `ref: refs/heads/<branch>`, which the SpoolBuddy remote-update
  69. # flow reads at runtime via detect_current_branch() in spoolbuddy_ssh.py.
  70. # Without this, the production image has no git metadata at all and would
  71. # always pull `main` on the remote device regardless of which branch
  72. # Bambuddy itself was built from.
  73. COPY .git/HEAD ./.git/HEAD
  74. # Copy built frontend from builder stage
  75. COPY --from=frontend-builder /app/static ./static
  76. # Copy embedded GCode viewer static assets (PrettyGCode + Bambuddy adapter).
  77. # Served by the explicit @app.get("/gcode-viewer/{...}") routes in main.py,
  78. # which resolve files under (static_dir.parent / "gcode_viewer") = /app/gcode_viewer/.
  79. # Without this COPY the routes return a bare 404 at request time and the 3D
  80. # Preview iframe shows {"detail":"Not Found"} (see #1218). The directory is
  81. # vendored third-party JS — the Vite build does NOT stage it into static/,
  82. # the dev server serves it via a configureServer middleware that's dev-only.
  83. COPY gcode_viewer/ ./gcode_viewer/
  84. # Create data directories. Ownership is normalised at startup by the
  85. # entrypoint (chowns to PUID:PGID and drops privileges via gosu before
  86. # exec'ing the app), so we don't need a chmod 777 hack here — that was
  87. # the workaround for the previous compose `user: "1000:1000"` model and
  88. # only worked when the volume's perms happened to survive (named volume
  89. # first-create case; bind-mount-source case bit users in #1211 / #668).
  90. #
  91. # The sentinel file is needed so a freshly-created Docker named volume
  92. # isn't "empty" from Docker's POV. On empty volumes Docker resyncs the
  93. # directory metadata (incl. ownership) from the image on every mount,
  94. # which would mean our entrypoint chown gets reverted on every restart
  95. # and re-fired on every start (slow on multi-GB archive dirs). With a
  96. # sentinel inside the volume on first mount, Docker considers the
  97. # volume populated and stops resyncing, so the chown is genuinely
  98. # one-shot.
  99. RUN mkdir -p /app/data /app/logs && \
  100. : >/app/data/.bambuddy && \
  101. : >/app/logs/.bambuddy
  102. # Entrypoint script: handles PUID/PGID + ownership normalisation +
  103. # privilege drop. See deploy/docker-entrypoint.sh for the full rationale.
  104. COPY deploy/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
  105. RUN chmod +x /usr/local/bin/docker-entrypoint.sh
  106. # Environment variables
  107. ENV PYTHONUNBUFFERED=1
  108. ENV DATA_DIR=/app/data
  109. ENV LOG_DIR=/app/logs
  110. ENV PORT=8000
  111. # Provide a local username + home for tools that call getpass.getuser() /
  112. # os.path.expanduser() under arbitrary PUIDs. With `user: "1001:1001"` the
  113. # stock python:3.13-slim image has no /etc/passwd entry for that UID, so
  114. # pwd.getpwuid() raises and breaks libraries that do host-level user lookups
  115. # (notably asyncssh, which uses the local username for ~/.ssh/config host
  116. # matching during the SpoolBuddy remote-update flow). Setting LOGNAME/USER
  117. # makes getpass.getuser() resolve via env vars instead of the passwd db;
  118. # HOME=/app gives a writable home that is guaranteed to exist.
  119. ENV HOME=/app
  120. ENV USER=bambuddy
  121. ENV LOGNAME=bambuddy
  122. # Matplotlib (imported lazily by the STL thumbnail generator) tries to create
  123. # its font/style cache at $HOME/.config/matplotlib on first import. /app is
  124. # root-owned and not writable by the PUID:PGID the entrypoint drops to,
  125. # which trips an EPERM warning in everyone's logs and forces matplotlib
  126. # to fall back to a per-restart temp dir (paying the font-scan cost on
  127. # every container restart). Pinning the cache dir to /tmp/matplotlib
  128. # silences the warning and keeps the cache alive for the container's
  129. # lifetime. /tmp is writable by any uid, so this works regardless of PUID.
  130. ENV MPLCONFIGDIR=/tmp/matplotlib
  131. EXPOSE 322
  132. EXPOSE 990
  133. EXPOSE 3000
  134. EXPOSE 3002
  135. EXPOSE 6000
  136. EXPOSE 8000
  137. EXPOSE 8883
  138. EXPOSE 50000-50100
  139. # Health check (uses PORT env var via shell)
  140. HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
  141. CMD python -c "import urllib.request, os; urllib.request.urlopen(f'http://localhost:{os.environ.get(\"PORT\", \"8000\")}/health')" || exit 1
  142. # Run the application
  143. # Use standard asyncio loop (uvloop has permission issues in some Docker environments)
  144. # Port is configurable via PORT (default 8000); bind address via HOST (default
  145. # 0.0.0.0). Set HOST=127.0.0.1 to bind loopback only, e.g. when a reverse proxy
  146. # on the same host fronts the app.
  147. #
  148. # `exec` is load-bearing, not style. Without it the shell stays as PID 1 and
  149. # uvicorn runs as its child; dash does not forward signals, so `docker stop`
  150. # SIGTERMs the shell and uvicorn never hears about it. Every stop then ran to
  151. # the end of the grace period and died on SIGKILL (exit 137) — no WAL
  152. # checkpoint, no MQTT disconnect, no virtual-printer teardown, on every restart
  153. # and every image update. With `exec`, uvicorn *is* PID 1 and gets the signal.
  154. #
  155. # --timeout-graceful-shutdown caps the wait on in-flight requests. Uvicorn's
  156. # default is to wait forever, and an MJPEG camera stream is a response that
  157. # never completes, so a single open camera tile would otherwise pin the process
  158. # past Docker's 10s grace and back into SIGKILL. On timeout uvicorn cancels the
  159. # request tasks; the camera generators already unwind cleanly on CancelledError.
  160. ENV UVICORN_TIMEOUT_GRACEFUL_SHUTDOWN=5
  161. ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
  162. CMD ["sh", "-c", "exec uvicorn backend.app.main:app --host ${HOST:-0.0.0.0} --port ${PORT:-8000} --loop asyncio --timeout-graceful-shutdown ${UVICORN_TIMEOUT_GRACEFUL_SHUTDOWN}"]