简体   繁体   中英

Set a Non-Root User by Dockerfile

I write a Dockerfile for creating a React Application

Dockerfile Instructions

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"]

these instructions give me error

#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

when I omit or comment

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

I can build the image

how to set a non-root user ?

Move the USER username statement to the end of the file, near the 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"]

Things that are COPY ed into an image by default are owned by root. This means that, for example, the npm ci step can't create a node_modules directory, because the parent /application directory is owned by root but in your setup you're doing work as the "username" user.

In the final image, though, you want your code and libraries to be owned by root, or at least, you want the current user to not have permissions to overwrite them. This protects you from accidentally changing things while the container is running, and limits the impact of some classes of bugs.

So the easiest way to get there in most images is to run your build as root, and then switch to a non-root user only to run the resulting container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM