Skip to content

Instantly share code, notes, and snippets.

@abstractvector
Last active April 25, 2023 13:57
Show Gist options
  • Save abstractvector/ed3f892ec0114e28b3d6dcdc4c39b1f2 to your computer and use it in GitHub Desktop.
Save abstractvector/ed3f892ec0114e28b3d6dcdc4c39b1f2 to your computer and use it in GitHub Desktop.
Lightweight node.js Dockerfile
ARG ALPINE_VERSION=3.11
ARG NODE_VERSION=15.5.1
##########################
# Cache-preserving image #
##########################
FROM alpine:${ALPINE_VERSION} AS deps
RUN apk --no-cache add jq
# prevent cache invalidation from changes in fields other than dependencies
COPY package.json .
COPY package-lock.json .
# override the current package version (arbitrarily set to 1.0.0) so it doesn't invalidate the build cache later
RUN (jq '{ dependencies, devDependencies }') < package.json > deps.json
RUN (jq '.version = "1.0.0"' | jq '.packages."".version = "1.0.0"') < package-lock.json > deps-lock.json
#################
# Builder image #
#################
FROM node:${NODE_VERSION} AS builder
WORKDIR /usr/src
COPY --from=deps deps.json ./package.json
COPY --from=deps deps-lock.json ./package-lock.json
RUN npm clean-install
COPY public/ public/
COPY src/ src/
COPY webpack/ webpack/
COPY package.json .
ENV NODE_ENV production
RUN npm run build
####################
# Production image #
####################
FROM node:${NODE_VERSION}-alpine${ALPINE_VERSION}
WORKDIR /usr/src
RUN chown node:node /usr/src && \
apk add --no-cache dumb-init
COPY --chown=node:node .env.example .
COPY --from=builder --chown=node:node /usr/src/dist/ dist/
COPY --from=builder --chown=node:node /usr/src/package.json .
ENV PORT 80
ENV NODE_ENV production
USER node
CMD ["dumb-init", "node", "dist/server"]
@CaseyLabs
Copy link

This is fantastic, using it as inspiration for a local dockerfile. Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment