簡體   English   中英

通過 Dockerfile 設置非 root 用戶

[英]Set a Non-Root User by Dockerfile

我寫了一個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到圖像中的東西歸根用戶所有。 這意味着,例如, npm ci步驟無法創建node_modules目錄,因為父/application目錄歸 root 所有,但在您的設置中,您以“用戶名”用戶身份工作。

但是,在最終圖像中,您希望您的代碼和庫由 root 擁有,或者至少,您希望當前用戶沒有權限覆蓋它們。 這可以防止您在容器運行時意外更改內容,並限制某些類別的錯誤的影響。

因此,在大多數鏡像中,最簡單的方法是以 root 身份運行構建,然后切換到非 root 用戶僅運行生成的容器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM