Dockerize the Node.js REST API

Docker packages the application and its runtime dependencies into a container image.

This makes it easier to run the same application across development, testing, and deployment environments.

Create a Dockerfile in the project root.

We will use a multi-stage build structure only if the application requires a build step. Since this is a plain JavaScript application, a simple production dependency installation is sufficient.

The container should run as a non-root user and should not include unnecessary development dependencies.

Dockerfile
FROM node:22-alpine

WORKDIR /app

COPY package*.json ./

RUN npm ci --omit=dev

COPY src ./src

ENV NODE_ENV=production

USER node

EXPOSE 3000

CMD ["node", "src/server.js"]

Creates a production container using Node.js Alpine, installs production dependencies, copies application source, and runs as a non-root user.

Key Takeaways
  • Docker packages the application into a container.

  • Install only production dependencies.

  • Run containers with non-root permissions.