通过Dockerfile设置非root用户



我写了一个Dockerfile用于创建React应用程序

Dockerfile指令

FROM node:16.13.1-alpine3.15
RUN npm i -g npm@8.6.0
RUN addgroup allusers && adduser -S -G allusers username
USER username
WORKDIR /application
COPY package*.json .
RUN npm i
COPY . .
EXPOSE 3003
CMD ["npm", "start"]

这些指令给我错误

#11 103.6 npm notice
#11 103.6 npm ERR! code EACCES
#11 103.6 npm ERR! syscall open
#11 103.6 npm ERR! path /application/package-lock.json
#11 103.6 npm ERR! errno -13
#11 103.6 npm ERR! Error: EACCES: permission denied, open '/application/package-lock.json'
#11 103.6 npm ERR!  [Error: EACCES: permission denied, open '/application/package-lock.json'] {
#11 103.6 npm ERR!   errno: -13,
#11 103.6 npm ERR!   code: 'EACCES',
#11 103.6 npm ERR!   syscall: 'open',
#11 103.6 npm ERR!   path: '/application/package-lock.json'
#11 103.6 npm ERR! }
#11 103.6 npm ERR!
#11 103.6 npm ERR! The operation was rejected by your operating system.
#11 103.6 npm ERR! It is likely you do not have the permissions to access this file as the current user
#11 103.6 npm ERR!
#11 103.6 npm ERR! If you believe this might be a permissions issue, please double-check the
#11 103.6 npm ERR! permissions of the file and its containing directories, or try running
#11 103.6 npm ERR! the command again as root/Administrator.
#11 103.6
#11 103.7 npm ERR! A complete log of this run can be found in:
#11 103.7 npm ERR!     /home/aliarya/.npm/_logs/2022-06-28T09_25_40_565Z-debug-0.log------
executor failed running [/bin/sh -c npm i]: exit code: 243
省略

时或

RUN addgroup allusers && adduser -S -G allusers username
USER username

我可以建立图像

如何设置非root用户

?

USER username语句移动到文件末尾,靠近CMD

RUN addgroup allusers && adduser -S -G allusers username
# still as root
...
RUN npm ci
...
# at the end of the file
USER username
CMD ["npm", "start"]

默认情况下COPY写入映像的内容归root所有。这意味着,例如,npm ci步骤不能创建node_modules目录,因为父/application目录由根目录拥有,但在您的设置中,您以"用户名"进行工作;用户。

在最后的图片中,你希望你的代码和库归root所有,或者至少,你希望当前用户没有覆盖它们的权限。这可以防止在容器运行时意外更改内容,并限制某些类错误的影响。

因此,在大多数映像中,最简单的方法是以root用户运行构建,然后切换到非root用户,仅运行生成的容器。

相关内容

  • 没有找到相关文章