Containerize your #nodejs application

Containerize your #nodejs application

ยท

2 min read

Set the base image

FROM node:20-alpine

Use the official Node.js container image in ๐˜ข๐˜ญ๐˜ฑ๐˜ช๐˜ฏ๐˜ฆ variant

Advantages of using minimal base images:

โžก๏ธ reduced attack surface thanks to fewer unnecessary packages and security vulnerabilities,
โžก๏ธ improved performance thanks to efficient disk space, memory and network utilization.

Set the working directory

WORKDIR /app

Set the working directory which defines the target location inside the container for all the subsequent instructions.

Copy and install depedencies

COPY package*.json /app

RUN npm install

Use ๐˜ฏ๐˜ฑ๐˜ฎ to install dependencies. By separating the dependencies from application source code you can take advantage of container layer caching. As long as you do not change the versions of libraries used by your application, the cached version of previously built layers will be reused, which will significantly shorten the build time.

Copy the application code

COPY --chown=node:node app.js /app

Copy the source code of your application to the working directory configured in the second step.

Run as non-privileged user

USER node

Ensure that processes running in your container will be executed in non-privileged mode. Since a non-privileged user called ๐˜ฏ๐˜ฐ๐˜ฅ๐˜ฆ is already registered in the base Node.js image, just use it.

Set the entry command

CMD ["node", "app.js"]

Finally, specify which application should be executed when the container starts.

complete Dockerfile

FROM node:20-alpine

WORKDIR /app

COPY package*.json /app
RUN npm install

COPY --chown=node:node app.js /app

USER node

CMD ["node", "app.js"]
ย