【问题标题】:EACCES: permission denied when adding user in DockerfileEACCES:在 Dockerfile 中添加用户时权限被拒绝
【发布时间】:2021-04-17 00:14:46
【问题描述】:

我在 typescript 中有一个 dockerized 项目,当我在 Dockerfile 中添加用户时,docker 容器失败并出现权限被拒绝错误。

我的dockerfile是这样的:

FROM node:14.5.0-alpine3.12

ADD . /src

WORKDIR /src

RUN npm install -g typescript

COPY package*.json ./

RUN npm install && \
    adduser -u ${USER_ID} --gecos '' --disabled-password --no-create-home user

RUN chown -R user /src

USER user

COPY . .

EXPOSE 8080

# Run node server
CMD npm run start

我的package.json 文件中的start 脚本具有以下值:rimraf ./dist && mkdir ./dist && tsc && node dist/index.js

因此,当我构建并运行容器时,它无法删除 dist 文件夹,并且出现以下错误:

[Error: EACCES: permission denied, rmdir 'dist/Util'] {
  errno: -13,
  code: 'EACCES',
  syscall: 'rmdir',
  path: 'dist/Util'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test-project@1.0.0 build: `rimraf ./dist && mkdir ./dist && tsc`
npm ERR! Exit status 1

我尝试在我的 Dockerfile 中添加 RUN chmod 777 /src/dist,但结果相同。

如何让用户授予写入权限?

【问题讨论】:

    标签: node.js typescript docker npm dockerfile


    【解决方案1】:

    这些构建步骤应该在您的 Dockerfile 中,然后再切换到 root 用户。我建议的设置更像以下:

    FROM node:14.5.0-alpine3.12
    WORKDIR /src
    
    # Create the user up front to save a little time on rebuilds.
    RUN adduser --gecos '' --disabled-password --no-create-home user
    
    # Copy _only_ the package.json in, to save substantial time on rebuilds.
    COPY package*.json ./     # includes "devDependencies": "typescript"
    RUN npm install
    
    # Copy the rest of the application in
    COPY . ./                 # .dockerignore includes node_modules
    
    # Build it
    RUN rimraf ./dist && tsc  # npm run build?
    
    # Set the non-root user and startup metadata
    USER user
    CMD ["node", "dist/index.js"]
    

    这将避免每次启动时都需要重新构建应用程序,特别是因为图像中的代码是固定的。

    【讨论】:

    • 因此无法授予用户访问权限,我们需要以 root 身份构建它。谢谢你的回答!
    • 只是一个简单的问题。如果在index.js 中想要写入带有fs 库的文件,那么我也必须在CMD 中使用root 并且根本不创建用户。有没有办法授予用户仅写入特定文件夹的权限?
    • 您可以创建具有不同所有权(或可能已安装卷)的data 子目录。
    猜你喜欢
    • 2020-06-03
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2015-07-20
    • 2016-03-14
    • 2016-11-14
    • 2014-01-24
    相关资源
    最近更新 更多