Qiulang
Qiulang

Reputation: 12395

How to make docker build (& Docerfile) respect the node version I set in package.json?

Our Node.js project requires Node version 14 or higher, so I set that in the package.json

  "engines": {
    "node": ">=14"
  }

But the Dockerfile (some other developer wrote it) did not respect that, it looks like these

FROM node:12-alpine3.14
COPY package*.json ./
ENV NODE_ENV production
# RUN npm install -g npm@latest
RUN npm install
...

docker build succeeded but docker run failed exactly because of node 12.

How can I make docker build respect the nodejs version I set in the package.json?

Please note that the problem is easily fixed by just update FROM node:14-alpine3.14. But that is not my question is about. For example, say in the future the project needs node16 and we update that in package.json but forget to update the Dockerfile, I need a way to make docker build failed for that reason.

Upvotes: 0

Views: 1368

Answers (1)

Qiulang
Qiulang

Reputation: 12395

I think make docker build failed is probably the only way (refer to Make docker build fail if tests fail too).

So I find 2 ways to do that.

A) By using RUN yarn instead of RUN npm install in the Dockerfile, so yarn will issue the error and docker build failed. Then by checking the failed message someone who builds the docker image will know the dockerfile needs to update.

#11 The engine "node" is incompatible with this module. Expected version ">=14". Got "12.22.8"
#11 1.363 error Found incompatible module.
#11 1.364 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
------
executor failed running [/bin/sh -c yarn]: exit code: 1

B) Create a .npmrc and set engine-strict=true so npm install will fail. Check How to specify/enforce a specific node.js version to use in package.json?

Upvotes: 1

Related Questions