Docker Template: Node.js
Summary
My unified docker template for Node.js apps. Supports:
- Development Environment:
--target dev
- CI:
--target test
- Production Environment:
--target release
. Uses an intermediatebuild
stage to prepare production builds. This helps to keep production image slim, containing onlynpm
packages & code builds. - Installation of private
npm
packages from github repositories. ExpectsGITHUB_TOKEN
as a docker build argument.
Dockerfile
# syntax=docker/dockerfile:1
# ---- Base ----
FROM node:16-alpine3.13 as base
ARG GITHUB_TOKEN
WORKDIR /app
COPY package.json ./
COPY yarn.lock ./
# ---- Dependencies ----
FROM base as dependencies
RUN apk add --no-cache openssh git
RUN if [[ "$GITHUB_TOKEN" != "" ]] ; then git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf ssh://git@github.com ; fi
RUN mkdir -p -m 0600 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts
COPY . .
# ---- Development ----
FROM dependencies AS dev
ENV NODE_ENV=development
CMD yarn install && yarn start:dev
# ---- Test ----
FROM dependencies AS test
ENV NODE_ENV=test
RUN yarn install
ENTRYPOINT yarn test
# ---- Production Build ----
FROM dependencies as build
RUN yarn install
RUN NODE_ENV=production yarn build
RUN rm -rf node_modules && yarn install --production
# ---- Release ----
FROM base AS release
ENV NODE_ENV=production
COPY --from=build --chown=node:node /app/dist ./dist
COPY --from=build --chown=node:node /app/node_modules ./node_modules
HEALTHCHECK CMD ls /proc/1/status || exit 1
USER node
CMD ["yarn", "start"]
SSH using BuildKit
Docker also allows the Docker Engine to forward host SSH agent connections. This can be done as:
RUN --mount=type=ssh yarn install
docker build --ssh default .
While this is the native docker solution to forward SSH agent, --ssh default
argument cannot still be passed down using docker compose
.
This makes it cumbersome to use in projects with multiple services needing hot reloading.
I use it when I am working on a monorepo.
However, if I am working with multiple services using docker compose
, I prefer adding GITHUB_TOKEN
.