给定一个设置自定义
USER
的 docker 镜像,如何挂载该自定义用户可写的主机目录?
我在使用预构建的 docker 映像时多次遇到这个问题,但我在这里重现一个最小的示例。
简单
Dockerfile
使用自定义USER
:
FROM ubuntu:22.04
RUN useradd -m -s /bin/bash mydockeruser
USER mydockeruser
尝试触摸主机上的文件:
docker run -it \
-v ./my-directory:/host \
my-ubuntu \
touch /host/test.txt
引发此错误:
touch: cannot touch '/host/test.txt': Permission denied
这是一个完整的脚本,显示了我的设置:
echo "Building my-ubuntu:"
docker build -t my-ubuntu .
########
# HOST #
########
rm -rf my-directory
mkdir my-directory
echo "$ ls -la my-directory:"
ls -la my-directory
echo "$ whoami:"
whoami
echo "$ id:"
id
##########
# DOCKER #
##########
echo "$ whoami (inside my-ubuntu):"
docker run -it \
-v ./my-directory:/host \
my-ubuntu \
whoami
echo "$ id (inside my-ubuntu):"
docker run -it \
-v ./my-directory:/host \
my-ubuntu \
id
echo "$ touch /host/test.txt (inside my-ubuntu):"
docker run -it \
-v ./my-directory:/host \
my-ubuntu \
touch /host/test.txt
输出:
Building my-ubuntu:
[+] Building 0.6s (6/6) FINISHED
[...]
$ ls -la my-directory:
total 8
drwxrwxr-x 2 myhostuser myhostuser 4096 Oct 7 12:46 .
drwxrwxr-x 3 myhostuser myhostuser 4096 Oct 7 12:46 ..
$ whoami:
myhostuser
$ id:
uid=1000(myhostuser) gid=1000(myhostuser) groups=1000(myhostuser),[...]
$ whoami (inside my-ubuntu):
mydockeruser
$ id (inside my-ubuntu):
uid=1000(mydockeruser) gid=1000(mydockeruser) groups=1000(mydockeruser)
$ touch /host/test.txt (inside my-ubuntu):
touch: cannot touch '/host/test.txt': Permission denied
注意:我使用的是
Ubuntu 20.04.6 LTS
和Docker version 27.3.1, build ce12230
,并且我使用dockerd-rootless-setuptool.sh install
安装了rootless docker。
添加
WORKDIR /host
FROM ubuntu:22.04
RUN useradd -m -s /bin/bash mydockeruser
USER mydockeruser
WORKDIR /host