Skip to content

Instantly share code, notes, and snippets.

@davideicardi
Created November 24, 2021 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davideicardi/542a1a0a2fa14515b09c1a2c19e2d536 to your computer and use it in GitHub Desktop.
Save davideicardi/542a1a0a2fa14515b09c1a2c19e2d536 to your computer and use it in GitHub Desktop.
Dockerfile template for node following best practices
# References:
# https://nodejs.org/en/docs/guides/nodejs-docker-webapp/
# https://github.com/nodejs/docker-node/blob/main/docs/BestPractices.md
# https://adambrodziak.pl/dockerfile-good-practices-for-node-and-npm
FROM node:16.13-alpine3.12 AS builder
WORKDIR /usr/src/app
# Set build environment
ENV NODE_ENV build
# Disable npm update notice (it seems to not work...)
ENV NO_UPDATE_NOTIFIER 1
# If/When installing global npm modules, put them outside of root user
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
ENV PATH=$PATH:/home/node/.npm-global/bin
# Install dependencies and run compilation
COPY package*.json ./
# RUN npm ci --only=production
RUN npm ci
# Copy all the other files
COPY . .
# Build and run unit tests
RUN npm run build \
&& npm run test \
&& npm run test:e2e
# Remove non prod modules
RUN npm prune --production
#######################
FROM node:16.13-alpine3.12 AS runtime
WORKDIR /usr/src/app
COPY --from=builder /usr/src/app/package*.json /usr/src/app/
COPY --from=builder /usr/src/app/node_modules/ /usr/src/app/node_modules/
COPY --from=builder /usr/src/app/dist/ /usr/src/app/dist/
# Set production environment by default but it can be overridden
ARG NODE_ENV=production
ENV NODE_ENV $NODE_ENV
# Run in non-root user (node user is created by base image)
RUN chown node:node ./
USER node
# Export port
EXPOSE 3000
# This will be executed inside Tini (https://github.com/krallin/tini), already present inside node image
CMD ["node", "dist/src/main"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment