Docker for NodeJS - 3. Node Dockerfile Best Practices

Dockerfile Best Practice Basics

FROM Base Image Guidelines

"The most important line in your Dockerfile"

Note: these guidelines refers to the use of the node image.

Assignment: Making a CentOS Node Image

This is an interesting exercise to create a Node image based on a not officially available base distro.

https://www.udemy.com/course/docker-mastery-for-nodejs/learn/lecture/13545434

The usefulness of the assignment is not exactly related to Node neither CentOS, but how to research things to build custom images.

Running non-root containers users

"Least privilege security with node user"

The trick below should be done:

# This is how to set `node` as the user
USER node

# After that, the RUN, CMD, and ENTRYPOINT run as the `node` user.
# This 👆 causes an issue when you use WORKDIR to create a directory.
# The workaround is to use this:
RUN mkdir directory && chown -R node:node .

If this causes permissions issues when using docker-compose, call it like this:

docker compose exec -u root
Important

After USER node, all executions of RUN, CMD and ENTRYPOINT run as the node user. All the other Dockerfile instructions are executed as root.

This video lecture is useful to show this behavior.

Making Images Efficiently

Look at this example:

# if this comes first, it'll be recreated a lot of times
COPY . .
RUN npm install && npm cache clean --force

You should do this instead:

# 1. copy only the "dependencies file"
COPY package.json package-lock.json* ./

# 2. install the dependencies
RUN npm install && npm cache clean --force

# 3. copy your code
COPY . .

Pro-tip: using package-lock.json* (with the trailing asterisk) makes the build NOT break if the file doesn't exist.