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"]