Skip to content

Instantly share code, notes, and snippets.

@arlyon
Created May 22, 2025 18:34
Show Gist options
  • Save arlyon/c48c39b61c518e03da4e13b3086b37e5 to your computer and use it in GitHub Desktop.
Save arlyon/c48c39b61c518e03da4e13b3086b37e5 to your computer and use it in GitHub Desktop.
The most optimized container on planet earth
FROM node:22 AS pnpm
WORKDIR /app
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV NODE_ENV="production"
COPY package.json .
RUN corepack enable
FROM pnpm AS base
RUN pnpm install -g turbo@latest
WORKDIR /app
COPY . .
RUN turbo prune --docker worker
RUN cp /app/tsconfig.json /app/out/full/tsconfig.json
FROM pnpm AS deps
COPY --from=base /app/out/json /app
WORKDIR /app
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile --prod=false
FROM deps as build
COPY --from=base /app/out/full /app
WORKDIR /app/apps/worker
RUN pnpm build
FROM build as prune
RUN pnpx node-jq '.outputs | to_entries | .[] | .value | .imports[] | select(.external) | .path' < dist/metafile-cjs.json | pnpx node-jq -sc unique > externals.json
RUN pnpm list --prod --json --depth Infinity | pnpx node-jq -r '.[] | .dependencies | to_entries[] | select(.key as $key | $data | any(.==$key)) | .value | recurse(.dependencies // {} | to_entries[] | .value | select(.from as $from | $banned | all(.!=$from))) | del(.dependencies) | [.from, .path] | join(",")' \
--argjson data $(cat externals.json) \
--argjson banned '["webpack", "@swc/core", "swc-loader", "@types/node", "typescript"]' \
| sort | uniq > externals
RUN <<-EOF
mkdir -p ./node_modules_pruned
cat externals | while IFS=, read -r FN SP || [ -n "$FN" ]; do
TGT="./node_modules_pruned/$FN"
mkdir -p "$(dirname "$TGT")"
cp -R "$SP" "$TGT"
done
EOF
FROM gcr.io/distroless/nodejs22-debian12:nonroot AS runner
WORKDIR /app
COPY --from=prune /app/apps/worker/node_modules_pruned ./node_modules
COPY --from=build /app/apps/worker/dist .
CMD ["--enable-source-maps", "index.cjs"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment