1 Commits
Author SHA1 Message Date
kennethobsequio 843fc38f12 perf(docker): slim api image from 1.44GB to 657MB
The api image shipped every build artifact pnpm produced:

  - pnpm store + caches            769 MB
  - ffprobe-static (5 platforms)   335 MB
  - devDependencies (jest et al.)  included
  - pm2, npm cache                 ~38 MB

Split the build into a deps stage that installs with --prod and drops the
pnpm store/caches in the same layer (node_modules entries are hardlinks, so
they survive), then copy only node_modules into a clean runtime stage.

ffprobe-static ships ffprobe for darwin/linux/win32 + ia32/x64 but both
services already prefer a system ffprobe via `which ffprobe`, so its binaries
are stripped and apk ffmpeg provides ffprobe instead. That also adds the
ffmpeg binary services/ffmpeg.service.js needs for the mov/mkv fast-start
remux, which the old image never had.

Drop pm2: docker's restart policy covers crashes, and node now receives
SIGTERM directly (~17 MB image, ~40 MB RSS saved on a 1.9 GB droplet).

Verified on the QAS droplet: clean build 98s (was ~3m54s deploy step),
code-only rebuild 8s, all runtime deps + sharp + typst + ffprobe resolve,
container boots to the DB handshake.

Also prune superseded layers in the deploy workflow.
2026-10-29 00:00:11 +08:00
6 changed files with 74 additions and 246 deletions
+6
View File
@@ -1,6 +1,12 @@
**/node_modules
.git
.github
.gitea
.env
.env.*
*.log
logs
coverage
**/coverage
docker-compose.yml
.dockerignore
+3
View File
@@ -97,4 +97,7 @@ jobs:
cp "$HOME/new_starr/.env" .env
docker compose -p new_starr up -d --build --remove-orphans
docker compose -p new_starr ps
# Reclaim space: superseded image layers and build cache older than 3 days.
docker image prune -f
docker builder prune -f --filter until=72h
REMOTE
+8 -7
View File
@@ -2,19 +2,20 @@
**Version:** 1.0.0
**Date:** October 6, 2025
**Stack:** Node.js · Express · Sequelize (PostgreSQL) · Google OAuth 2.0 · Nodemailer
**Features** Courses, Units, Lessons, Training, Subscriptions
**Features:** Courses, Units, Lessons, Training, Subscriptionss)
## Contributing
We remind everyone to work with `dev/safe` branch and we recommend to have your own forked repository here's breakdown:
Every contributors must take note that we have [Gitea](https://gitea.orij.space/kennethscoffee/starr-philproperties) owned by us independently so create your account here, We expect that you are in `dev/safe` branch so we recommend to have your own forked repository in Gitea here's summary:
```
BRANCH_NAME | DESCRIPTION
-------------------------
main - Protected branch supposedly maintain by creators
staging-qa - Everytime na may Pull Requests (PR) from your forked repository dito mismo sa branch na ito kami mag-check per feature, per modification and also bug.
staging-uat - Supposedly has working Github Action so I will tell about it.
dev/safe - In your forked repository always use this branch
main - A protected branch maintain by creators (Any commits from other will be automatically rejected)
staging-qa - Everytime na may Pull Requests (PR) from your forked repository dito mismo
sa branch na ito kami mag-check per feature, per modification and also bug.
staging-uat - Working in progress so I will tell more about it.
dev/safe - With your forked repository this is default branch
```
## Self-hosting
See [SELF_HOSTING.md](./SELF_HOSTING.md) for the full Docker Compose setup guide.
See [Wiki](https://gitea.orij.space/kennethscoffee/starr-philproperties/wiki/Self-hosting-%28Docker%29)
-226
View File
@@ -1,226 +0,0 @@
# Self-Hosting `new_starr` (Docker Compose) — Step-by-Step
### ***Video tutorial soon***
This stack bundles everything: PostgreSQL, Valkey (Redis), Garage (S3), the API, and the
frontend. Battle-tested end-to-end on a completely fresh Debian machine on 2026-08-29
every gotcha below actually happened once and is now fixed or documented.
---
## 0. What you need
- Docker Engine + Compose plugin
- Node.js 22 + pnpm (only needed once, to build the frontend bundle)
- Git access to this repo
---
## 1. Install Docker
This block auto-detects `debian` vs `ubuntu` from `/etc/os-release` **and** probes
Docker's repo for your codename before adding it — if your codename is too new and 404s
(interim/dev releases lag Docker's repo by months), it automatically falls back to the
latest codename Docker actually publishes for your distro. No manual edits needed:
```bash
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
. /etc/os-release
DOCKER_DISTRO="$ID" # debian or ubuntu
DOCKER_CODENAME="$VERSION_CODENAME"
# Fallback list, newest first, per distro — used only if the detected codename 404s
case "$DOCKER_DISTRO" in
ubuntu) FALLBACKS="noble jammy focal" ;;
debian) FALLBACKS="bookworm bullseye" ;;
*) echo "Unsupported distro '$DOCKER_DISTRO' — Docker only publishes debian/ubuntu repos." >&2; exit 1 ;;
esac
if ! curl -fsSL -o /dev/null "https://download.docker.com/linux/${DOCKER_DISTRO}/dists/${DOCKER_CODENAME}/Release"; then
echo "Docker has no repo for ${DOCKER_DISTRO} ${DOCKER_CODENAME} yet, falling back..." >&2
for fb in $FALLBACKS; do
if curl -fsSL -o /dev/null "https://download.docker.com/linux/${DOCKER_DISTRO}/dists/${fb}/Release"; then
DOCKER_CODENAME="$fb"
break
fi
done
echo "Using ${DOCKER_DISTRO} ${DOCKER_CODENAME}" >&2
fi
curl -fsSL "https://download.docker.com/linux/${DOCKER_DISTRO}/gpg" | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/${DOCKER_DISTRO} \
${DOCKER_CODENAME} stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
```
(The `FALLBACKS` lists above are current as of 2026-08 — bump them if Docker ships a
newer stable codename by the time you read this.)
Let your user run Docker without `sudo`:
```bash
sudo usermod -aG docker $USER
newgrp docker
docker compose version # sanity check
```
---
## 2. Clone & install
```bash
git clone git@github.com:rgrgogu/new_starr.git
cd new_starr
corepack enable && corepack prepare pnpm@11.3.0 --activate
pnpm install
```
---
## 3. Configure environment — **three** files, not two
### `apps/api/.env`
```bash
cp apps/api/.env-production apps/api/.env
```
Fill in every `CHANGE_ME`. For a **local bundled stack** (as opposed to CockroachDB
Cloud / managed S3), these specific values matter:
```env
DB_HOST=postgres
DB_PORT=5432
DB_SSL=false # bundled Postgres has no TLS
CACHE_DRIVER=redis
REDIS_URL=redis://valkey:6379
S3_ENDPOINT=http://garage:3900
GARAGE_RPC_SECRET=<openssl rand -hex 32>
```
Generate every secret independently:
```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```
### `apps/web/.env`
```bash
cd apps/web && cp .env.example .env
```
Fill in `VITE_API_URL`, `VITE_APP_URL`, etc., then `cd ../..`.
### Root `new_starr/.env` — easy to miss, causes silent failures
`docker-compose.yml`'s bundled `postgres` service reads `${DB_NAME}`, `${DB_USER}`,
`${DB_PASSWORD}` from a **root-level** `.env` — NOT from `apps/api/.env`. Create it
separately, with **exactly the same values** as the DB block you just put in
`apps/api/.env`:
```env
DB_NAME=starr
DB_USER=starr
DB_PASSWORD=<same password as apps/api/.env>
```
⚠️ Postgres only reads these once, at first-ever container start, and bakes them into
its data volume. If the two files ever drift apart afterward, you'll get
`password authentication failed` even though everything "looks" configured — fix by
making `apps/api/.env` match what's actually in the volume (the root `.env` value at
the time Postgres first started), not the other way around.
---
## 4. Build the frontend bundle *before* building images
`apps/web/Dockerfile` only copies a pre-built `dist/` — it does not run the build itself:
```bash
pnpm --filter web build
```
---
## 5. Bring the stack up
```bash
docker compose up -d --build
docker compose ps # all 5 services should show Up/healthy
```
---
## 6. One-time Garage (S3) cluster init
Garage's image ships only a static binary — no shell — so this can't be scripted as a
container entrypoint; it's a manual one-time step:
```bash
docker compose exec garage /garage node id
```
Copy the ID (the part **before** the `@host:port`), then:
```bash
docker compose exec garage /garage layout assign <NODE_ID> -z dc1 -c 100G
docker compose exec garage /garage layout apply --version 1
docker compose exec garage /garage bucket create <S3_BUCKET>
docker compose exec garage /garage key import <S3_ACCESS_KEY> <S3_SECRET_KEY> -n starr-app --yes
docker compose exec garage /garage bucket allow <S3_BUCKET> --read --write --owner --key <S3_ACCESS_KEY>
```
(`S3_BUCKET`/`S3_ACCESS_KEY`/`S3_SECRET_KEY` are whatever you set in `apps/api/.env`.)
---
## 7. Run database migrations
```bash
docker compose exec backend sequelize-cli db:migrate
```
---
## 8. Verify
```bash
docker compose ps
```
- Frontend: **http://localhost:4650**
- Backend: http://localhost:3024/api
If both respond, you're done with local testing.
---
## 9. (Optional) Put a real domain + HTTPS in front
For actually deploying this somewhere reachable, use the `Caddyfile` at the repo root
as a template. It's a standalone Caddy install on the host (not part of
`docker-compose.yml`) that reverse-proxies 3 domains to the 3 ports already published
above (`:4650`, `:3024`, `:3900`) and handles Let's Encrypt certificates automatically.
See the comments at the top of `Caddyfile` for exact steps. Not needed for local
`localhost:4650` testing — skip this until you're pointing a real domain at the
machine.
---
## Troubleshooting — real errors hit while writing this guide
| Symptom | Cause | Fix |
|---|---|---|
| `apt` 404: `.../linux/<distro> <codename> Release` not found | Step 1's install block already auto-detects and falls back — this only happens if you ran the old manual commands, or your codename is newer than every entry in `FALLBACKS` | Re-run Step 1's block as-is, or add your distro's actual latest stable codename to `FALLBACKS` |
| `permission denied ... docker.sock` | User not in the `docker` group | `sudo usermod -aG docker $USER && newgrp docker` |
| `WARN: "DB_NAME" variable is not set` (and similar) | Root `new_starr/.env` missing | Create it (see step 3) |
| `postgres` container stuck `Restarting` | `POSTGRES_PASSWORD` blank (same root `.env` issue) | Same fix as above |
| `exec: "/bin/sh": stat /bin/sh: no such file or directory` | Some images (like Garage's) ship no shell at all — never wrap their entrypoint in `/bin/sh` | Use the image's default command; do cluster setup via `docker exec <container> <binary>` directly (no shell needed) |
| Garage crash-loops: `rpc_secret value is missing` | `GARAGE_RPC_SECRET` not set in `apps/api/.env` | Set it, then `docker compose up -d --force-recreate garage` |
| `password authentication failed for user ...` | `apps/api/.env` and root `.env` DB passwords don't match exactly | Make them match; Postgres only honors whatever was set at first boot |
| Fixed a file but the same error keeps happening | Images bake in code at **build** time — there's no live volume mount | `docker compose up -d --build <service>` after any source change |
| `ERROR: Unknown constraint error` during migrate | Sequelize hides the real Postgres error behind this generic message | Run the raw SQL directly via `docker compose exec postgres psql -U <user> -d <db>` to see the actual cause |
| Migration uses `STRING` as a raw SQL type | CockroachDB alias, not valid in real Postgres | Already fixed in this repo (swapped to `TEXT`, which works on both) |
| A service vanishes from `docker compose ps` | A previous `up` was scoped to one service (e.g. `up -d --build backend`), which doesn't touch others | Run a plain `docker compose up -d` (no service name) to restore everything |
| Browser: "Unable to connect" | Either the container isn't actually running, or you're browsing from a different machine than the one running Docker | Check `docker compose ps` first; `localhost` only resolves to the machine Docker is on |
---
## Notes
- Frontend is served on **`:4650`**, not `:80` — change `frontend.ports` in
`docker-compose.yml` if you want a different port.
- Cluster init for Garage is intentionally manual (step 6) — the old automated
`garage-init.sh` approach was removed because it depended on a shell that doesn't
exist in the Garage image.
+53 -12
View File
@@ -1,29 +1,70 @@
FROM pandoc/typst:latest-alpine AS typst
# syntax=docker/dockerfile:1
FROM node:22-alpine
# Enable corepack and activate pnpm
RUN corepack enable && corepack prepare pnpm@11.3.0 --activate
# pm2 manages the process; sequelize-cli runs migrations on startup
RUN npm install -g pm2 sequelize-cli
# ─────────────────────────────────────────────────────────────────────────────
# api — production image
#
# Two stages. `deps` installs production dependencies only, then the final
# stage receives just the runtime artifacts. Everything pnpm keeps for
# itself (content-addressable store, metadata cache, npm cache) stays behind
# in the build stage, so it never inflates the shipped image.
# ─────────────────────────────────────────────────────────────────────────────
# Typst — compiles certificate.typ into the downloadable PDF certificate.
# Not available as an apk package, so lift the binary out of pandoc/typst.
COPY --from=typst /usr/local/bin/typst /usr/local/bin/typst
FROM pandoc/typst:latest-alpine AS typst
# ── Stage 1: dependencies (production only) ──────────────────────────────────
FROM node:22-alpine AS deps
RUN corepack enable && corepack prepare pnpm@11.3.0 --activate
WORKDIR /app
# Workspace manifests first (cache-friendly), then a filtered install —
# pnpm needs every workspace package's manifest present to resolve the
# graph even though only apps/api's deps get installed here. pnpm-lock.yaml
# is gitignored (not committed), so this resolves fresh on every build
# rather than installing from a frozen lockfile.
# is gitignored (not committed), so this resolves fresh rather than
# installing from a frozen lockfile.
COPY package.json pnpm-workspace.yaml ./
COPY apps/api/package.json ./apps/api/package.json
COPY apps/web/package.json ./apps/web/package.json
RUN pnpm install --filter api...
# --prod skips jest / nodemon / concurrently. The pnpm store is deleted in
# the same layer: node_modules entries are hardlinks, so they survive the
# delete while ~500 MB of duplicate store files do not.
#
# ffprobe-static ships ffprobe for darwin/linux/win32 + ia32/x64 (~335 MB).
# The runtime image installs the distro ffmpeg instead (see below), which both
# services prefer via `which ffprobe`, so only the package stub is kept.
RUN pnpm install --filter api... --prod --no-frozen-lockfile \
&& rm -rf /root/.local/share/pnpm /root/.cache/pnpm /root/.cache/node /root/.npm \
&& rm -rf /app/node_modules/.pnpm/ffprobe-static@*/node_modules/ffprobe-static/bin
# ── Stage 2: runtime ─────────────────────────────────────────────────────────
FROM node:22-alpine
# sequelize-cli stays available for manual `db:migrate` runs on the droplet;
# the npm cache is cleared in the same layer so it never ships.
#
# ffmpeg brings ffprobe with it and is what the mov/mkv fast-start remux
# (services/ffmpeg.service.js) actually needs — ffprobe-static never shipped an
# ffmpeg binary. Costs ~100 MB unpacked (libavcodec/x265/aom), still far less
# than the 335 MB of removed ffprobe-static binaries.
RUN apk add --no-cache ffmpeg \
&& npm install -g --no-audit --no-fund sequelize-cli@^6.6.5 \
&& npm cache clean --force \
&& rm -rf /root/.npm
COPY --from=typst /usr/local/bin/typst /usr/local/bin/typst
WORKDIR /app
# Symlinks inside pnpm's node_modules are relative, so copying the same
# directory layout keeps them resolving correctly.
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/api/node_modules ./apps/api/node_modules
COPY package.json pnpm-workspace.yaml ./
COPY apps/api ./apps/api
WORKDIR /app/apps/api
+4 -1
View File
@@ -1,4 +1,7 @@
#!/bin/sh
set -e
exec pm2-runtime start server.js --name "${APP_NAME:-app}"
# Docker's `restart: unless-stopped` policy handles crash recovery, so the
# process supervisor (pm2) is not shipped — it costs image size and ~40 MB RSS
# on a 2 GB droplet. node runs as PID 1 and receives SIGTERM directly.
exec node server.js