You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

以本地主机用户身份运行Docker并挂载文件夹权限问题

问题:无根Docker挂载本地文件夹权限异常

环境与需求

  • 本地目录结构:
- home
-- my_user
---- work
------ projects
-------- code
  • 需求:运行Docker容器挂载code文件夹,确保容器内创建/访问的文件,本地用户仍拥有所有权
  • Docker运行模式:无根模式(rootless mode)

我的配置与操作

Dockerfile内容

FROM ubuntu

ARG UID
ARG GID
ARG USERNAME

# Install necessary packages including python3-virtualenv and pip
RUN apt-get update && apt-get install -y \
    sudo \
    wget \
    python3 \
    python3-pip \
    python3-virtualenv \
    python3-dev \
    build-essential \
    git
RUN ln -sf /usr/bin/python3 /usr/bin/python && \
    ln -sf /usr/bin/pip3 /usr/bin/pip

# Create a group with the specified GID
RUN groupadd -g ${GID} ${USERNAME}
# Create a user with the specified UID and GID (-d creates home folder, -s selects shell)
RUN useradd -d /home/${USERNAME} -u ${UID} -g ${GID} -s /bin/bash ${USERNAME}
# Add the user to the sudoers file
RUN echo "${USERNAME} ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
RUN mkdir /home/${USERNAME}/code && chown ${USERNAME} /home/${USERNAME}/code
RUN echo "${USERNAME}"
USER ${USERNAME}

构建镜像命令

docker build --build-arg UID=$(id -u) --build-arg GID=$(id -g) --build-arg USERNAME=$(whoami) -t image_name -f Dockerfile .

运行容器命令

docker run -it -v /home/my_user/work/projects/code/:/home/my_user/code image_name

异常情况

进入容器后,用户名、UID、GID均与本地主机一致,但查看code文件夹权限时,发现其仍归属root用户:

total 8
drwxrwxr-x 10 root root 4096 Jul 11 14:41 code

尝试执行chown命令修改权限:

chown -R my_user code/

但所有文件都返回权限错误:

chown: changing ownership of 'code/xxx': Operation not permitted

内容的提问来源于stack exchange,提问作者Carlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 00:21:06