NodeJS API Dockerfile
# Naive Implementation
FROM NODE
COPY . .
RUN npm install
CMD ["node", "index.js"]
# Better Implementation
FROM node:19.6-bullseye-slim
COPY . .
RUN npm install
CMD ["node", "index.js"]
# With Working Directory
FROM node:19.6-bullseye-slim
WORKDIR /usr/src/app
COPY . .
RUN npm install
CMD ["node", "index.js"]
FROM node:19.6-bullseye-slim
WORKDIR /usr/src/app
COPY package*.json ./
COPY ./src/ .
CMD ["node", "index.js"]
# Use a non-root USER
FROM node:19.6-bullseye-slim
ENV NODE_ENV production // environment for production
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production // npm clean install is better
USER node
COPY --chown=node:node ./src/ .
CMD ["node", "index.js"]
# Use a non-root USER
FROM node:19.6-bullseye-slim
LABEL org.opencontainers.image.authors="email"
ENV NODE_ENV production // environment for production
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production // npm clean install is better
USER node
COPY --chown=node:node ./src/ .
EXPOSE 3000 // command tells the end users the port number that the containerized application expects to listen on
CMD ["node", "index.js"]
Using a Cache Mount to Speed up dependency installation
BuildKit provides features - cache mount for specific RUN instructions within a Dockerfile, so that changing dependency wont require re-downloading all dependencies from the internet.
Multistage Docker Setup
#------------------------------------------- # Name the first stage "base" to reference later FROM node:19.6-bullseye-slim AS base #------------------------------------------- LABEL org.opencontainers.image.authors="sid@devopsdirective.com" WORKDIR /usr/src/app COPY package*.json ./ #------------------------------------------- # Use the base stage to create dev image FROM base AS dev #------------------------------------------- RUN --mount=type=cache,target=/usr/src/app/.npm \ npm set cache /usr/src/app/.npm && \ npm install COPY . . CMD ["npm", "run", "dev"] #------------------------------------------- # Use the base stage to create separate production image FROM base AS production #------------------------------------------- ENV NODE_ENV production RUN --mount=type=cache,target=/usr/src/app/.npm \ npm set cache /usr/src/app/.npm && \ npm ci --only=production USER node COPY --chown=node:node ./src/ . EXPOSE 3000 CMD [ "node", "index.js" ]