Docker中NPM报错could not get uid/gid错误

问题描述

最近在 Docker 使用 NPM 安装 pm2 中出现could not get uid/gid错误,错误详情如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Error: could not get uid/gid
[ 'nobody', 0 ]

at /usr/local/lib/node_modules/npm/node_modules/uid-number/uid-number.js:37:16
at ChildProcess.exithandler (child_process.js:296:5)
at ChildProcess.emit (events.js:182:13)
at maybeClose (internal/child_process.js:962:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
TypeError: Cannot read property 'get' of undefined
at errorHandler (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:205:18)
at /usr/local/lib/node_modules/npm/bin/npm-cli.js:78:20
at cb (/usr/local/lib/node_modules/npm/lib/npm.js:228:22)
at /usr/local/lib/node_modules/npm/lib/npm.js:266:24
at /usr/local/lib/node_modules/npm/lib/config/core.js:83:7
at Array.forEach (<anonymous>)
at /usr/local/lib/node_modules/npm/lib/config/core.js:82:13
at f (/usr/local/lib/node_modules/npm/node_modules/once/once.js:25:25)
at afterExtras (/usr/local/lib/node_modules/npm/lib/config/core.js:173:20)
at Conf.<anonymous> (/usr/local/lib/node_modules/npm/lib/config/core.js:231:22)
/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:205
if (npm.config.get('json')) {
^

TypeError: Cannot read property 'get' of undefined
at process.errorHandler (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:205:18)
at process.emit (events.js:182:13)
at process._fatalException (internal/bootstrap/node.js:491:27)

解决方案

  • npm install 前加上npm config set unsafe-perm true
  • 使用用 cli 参数 npm i XX --unsafe-perm

unsafe-perm 配置

查阅npm相关文档:
unsafe-perm

  • Default: false if running as root, true otherwise
  • Type: Boolean

Set to true to suppress the UID/GID switching when running package scripts. If set explicitly to false, then installing as a non-root user will fail.

针对 unix 平台,使用 root 用户执行 npm 命令时得到的默认值都会是 false。

我的理解大致是避免以 root 的身份去执行时可能造成的安全问题。

参考文档

#20861
npm
What does unsafe-perm in npm actually do?