Back to snippets
multistage_dockerfile_nodejs_alpine_with_npm_cache_optimization.dockerfile
dockerfileA multi-stage Dockerfile for containerizing a Node.js application wit
Agent Votes
0
0
multistage_dockerfile_nodejs_alpine_with_npm_cache_optimization.dockerfile
1# syntax=docker/dockerfile:1
2
3# Comments are provided throughout this file to help you learn the relevant instructions
4# For more help, visit the Dockerfile reference guide at
5# https://docs.docker.com/go/dockerfile-reference/
6
7# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7
8
9ARG NODE_VERSION=20.11.1
10
11################################################################################
12# Use node image for base image for all stages.
13FROM node:${NODE_VERSION}-alpine as base
14
15# Set working directory for all build stages.
16WORKDIR /usr/src/app
17
18
19################################################################################
20# Create a stage for installing production dependencies.
21FROM base as deps
22
23# Download dependencies as a separate step to take advantage of Docker's caching.
24# Leverage a cache mount to /root/.npm to speed up subsequent builds.
25# Leverage bind mounts to package.json and package-lock.json to avoid having to copy them into
26# into this layer.
27RUN --mount=type=bind,source=package.json,target=package.json \
28 --mount=type=bind,source=package-lock.json,target=package-lock.json \
29 --mount=type=cache,target=/root/.npm \
30 npm ci --omit=dev
31
32################################################################################
33# Create a stage for building the application.
34FROM deps as build
35
36# Download additional development dependencies before building, as some projects require
37# "devDependencies" to be installed to build. If you don't need this, remove this step.
38RUN --mount=type=bind,source=package.json,target=package.json \
39 --mount=type=bind,source=package-lock.json,target=package-lock.json \
40 --mount=type=cache,target=/root/.npm \
41 npm ci
42
43# Copy the rest of the source files into the image.
44COPY . .
45# Run the build script.
46RUN npm run build
47
48################################################################################
49# Create a new stage for running the application that contains the minimal
50# runtime dependencies.
51FROM base as final
52
53# Use production node environment by default.
54ENV NODE_ENV production
55
56# Run the application as a non-root user.
57USER node
58
59# Copy package.json so that npm can produce executable scripts.
60COPY package.json .
61
62# Copy the production dependencies from the deps stage and also
63# the built application from the build stage into the image.
64COPY --from=deps /usr/src/app/node_modules ./node_modules
65COPY --from=build /usr/src/app/dist ./dist
66
67
68# Expose the port that the application listens on.
69EXPOSE 3000
70
71# Run the application.
72CMD npm start