Skip to content

Instantly share code, notes, and snippets.

@rafa-thayto
Last active March 4, 2024 03:51
Show Gist options
  • Save rafa-thayto/9dcaa2dc64ba071b3e123fcb0f5dc6f5 to your computer and use it in GitHub Desktop.
Save rafa-thayto/9dcaa2dc64ba071b3e123fcb0f5dc6f5 to your computer and use it in GitHub Desktop.
Lightweight Dockerfile for nodejs apps with multi-staged builds
# Base image
FROM node:PUT_THE_IMAGE_HERE AS base
# Install dependencies
FROM base as deps
WORKDIR /app
# ARG GH_TOKEN
# Change the registry if needed
# RUN npm config set <THE_REGISTRY>:registry https://npm.pkg.github.com && \
# npm config set //npm.pkg.github.com/:_authToken '${GH_TOKEN}'
# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
if [ -f yarn.lock ]; then yarn --frozen-lockfile --production; \
elif [ -f package-lock.json ]; then npm ci --production; \
elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile --prod; \
else echo "Lockfile not found." && exit 1; \
fi
# Rebuild the source code only when needed
FROM base as build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Production image, copy all the files and run application
FROM base as runner
WORKDIR /app
COPY --from=deps /app/package.json ./package.json
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
# Change the PORT if needed
EXPOSE 3000
ENTRYPOINT [ "sh", "entrypoint.sh" ]
#!/bin/sh
echo 'Starting the container...'
# npm start or node FOO_BAR
# Base image
FROM node:20-bullseye-slim AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
# Change the registry if needed
# RUN npm config set <THE_REGISTRY>:registry https://npm.pkg.github.com && \
# npm config set //npm.pkg.github.com/:_authToken "${GH_TOKEN}"
COPY . /app
WORKDIR /app
FROM base AS prod-deps
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --prod --frozen-lockfile --ignore-scripts
FROM base AS build
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile --ignore-scripts && \
pnpm build
# Production image, copy all the files and run application
FROM node:20-bullseye-slim as runner
WORKDIR /app
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 fastify
COPY --from=prod-deps --chown=fastify:nodejs /app/node_modules /app/node_modules
COPY --from=build --chown=fastify:nodejs /app/dist /app/entrypoint.sh ./
USER fastify
EXPOSE 3000
ENTRYPOINT [ "sh", "entrypoint.sh" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment