'Docker npm install --production not working
I have a dockerfile where I am using alpine-nodejs version 16 as the base image. The npm version is 8.
When the step of npm install --production
is executed while doing docker build
, it is also installing dependencies listed under dev-dependencies of package.json, contrary to the use-case of production flag.
I also used npm install --only=production
but that also doesn't seem to work.
With alpine nodejs version 14, the flag is working as expected and dev-dependencies are not getting installed in container. Is there any issue with alpine node version 16 image? Thanks.
Solution 1:[1]
After struggling on this for weeks, I have finally found the root cause and it is really dumb of me to not pay attention to that, I don't want others to make the same mistake. Since the code is proprietary, I can't share it. But I will explain the problem.
The image with nodejs:16
uses npm
8.0 whereas the one with nodejs:14
uses some npm
version < 8.0.
The difference between them is in version 8.0, npm
will also install the dependencies listed within peerDependencies
block. (I am unsure if this behavior started from npm 8.0 or some previous versions)
So, why'd I think npm is installing both devDependencies as well as dependencies?
When I was working with the nodejs:14
image, I moved certain dependencies from dependencies block to devDependencies block. So, when I upgraded to nodejs:16
, those dependencies returned.
Actually, the reason they came back because they were being internally used by a dependency(transitive dependency), which was listed within peerDependency
block of package.json
.
So, the takehome lesson ?
Make sure the dependency you want to be removed isn't being consumed directly or transitively within dependency
as well as peerDependency
block.
Solution 2:[2]
I suspect your Dockerfile
probably has something like COPY . .
but you don't set .dockerignore
correctly, e.g. you didn't add node_modules
to your .dockerignore
(check COPY with docker but with exclusion for the further information about .dockerignore
)
I made the same mistake too and it should have nothing do with nodejs14 or nodejs16
BTW, npm install --only=prod[uction]
is npm 6.x format and npm install --production
is npm 8.x format. One difference is that in npm 8.x if you set NODE_ENV production
npm 8.x will only install dependencies even if you run npm install
but for npm6.x npm install --only
will ignore NODE_ENV
Solution 3:[3]
It seems that npm ignores --production (or equivalent) flags when package-lock.json
file is present.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |
Solution 2 | Qiulang |
Solution 3 | Dragas |