COPY
, not ADD
npm
or yarn
that comes with the image (do not reinstall them unnecessarily)RUN npm install && npm cache clean --force
so the image is small as possibleCMD
use node
, not npm
.
npm
is bad because it...
package.json
)WORKDIR
, not RUN mkdir
(unless you need chown
)"The most important line in your Dockerfile"
Note: these guidelines refers to the use of the node
image.
:latest
:slim
:onbuild
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.
"Least privilege security with node user"
node
images have a node userapt install
, or npm install --global
).The trick below should be done:
apt
, apk
and npm i -g
npm i
chown node:node
# 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
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.
FROM
(preferably an alpine based image)COPY
twice: package.json
then . .
apt
/apk
should come at the topLook 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.