NPM 在 docker 容器中升级后中断

NPM breaks after it has been upgraded in docker container

我需要使用节点 v6.10.3 创建一个 docker 容器,但使用最新的 npm(目前 v5.4.1)来为本地包使用新的 npm 功能。

这样的安装在我的 Mac 上运行没有任何问题,但是当我尝试使用这样的安装创建一个 docker 图像时,在更新 npm 之后,npm 工具被破坏并抛出一堆关于丢失包的错误数。

这里是 Dockerfile 的例子,我可以用它重现这个问题(注意我的真实 Dockerfile 更复杂):

FROM ubuntu:xenial

RUN apt-get update
RUN apt-get install -y curl

RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs

RUN npm i -g npm
RUN npm i -g lerna

当构建过程到达 RUN npm i -g lerna 行时,它会抛出一堆错误,例如:

Error: Cannot find module 'process-nextick-args'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/lib/node_modules/npm/node_modules/readable-stream/lib/_stream_readable.js:26:23)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

任何其他 npm 脚本都会导致相同的错误。重新安装 npm 依赖的所有包,对我来说似乎不是一个解决方案。

我也尝试过使用 nvm 在容器中安装节点,但我遇到了同样的错误。

我的docker版本:

Docker version 17.06.2-ce, build cec0b72

这个 Dockerfile 有什么问题,我错过了什么?

我找到了解决此问题的方法,使用 yarn

它看起来很奇怪,但它确实有效:

FROM ubuntu:xenial

RUN apt-get update
RUN apt-get install -y curl

RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs

RUN npm i -g yarn
RUN npm uninstall npm -g
RUN yarn global add npm
RUN npm i -g lerna

不过,如果有人能解释为什么原来的解决方案不起作用,那就太好了,and/or帮助找到更好的解决方法。