Dockerfile 将主机用户 UID 和 GID 复制到镜像 [英] Dockerfile replicate the host user UID and GID to the image

查看:41
本文介绍了Dockerfile 将主机用户 UID 和 GID 复制到镜像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于 关于从主机复制容器中的 UID/GID 的帖子,但是如何使用具有复制 UID 和 GID 的用户?最好,你如何使用 dockerfile 来做这件事?

Similar to the SO post about replicating UID/GID in container from host but how do you build the image with a user with replicate UID and GID? Preferably, how do you do it with a dockerfile?

我可以使用 bash 脚本来完成:

I can do it with a bash script:

#!/bin/bash

# current uid and gid
curr_uid=`id -u`
curr_gid=`id -g`

# create bb.dockerfile:
cat << EOF1 > bb.dockerfile
 FROM ubuntu:xenial-20170214
 ARG UNAME=testuser
EOF1

 echo ARG UID=${curr_uid} >> bb.dockerfile
 echo ARG GID=${curr_gid} >> bb.dockerfile

cat << EOF2 >> bb.dockerfile
 RUN groupadd -g $GID $UNAME
 RUN useradd -m -u $UID -g $GID -s /bin/bash $UNAME
 USER $UNAME
 CMD /bin/bash
EOF2

docker build -f bb.dockerfile -t testimg .

这个 bash 将生成一个如下所示的 docker 文件并在其上构建.

This bash will generate a docker file as the following and build on it.

 FROM ubuntu:xenial-20170214
 ARG UNAME=testuser
 ARG UID=1982
 ARG GID=1982
 RUN groupadd -g $GID $UNAME
 RUN useradd -m -u $UID -g $GID -s /bin/bash $UNAME
 USER $UNAME
 CMD /bin/bash

我要的是从 dockerfile 中删除硬编码的主机 UID 1982 和 GID 1982.

What I'm asking for, is to remove the hardcoded host UID 1982 and GID 1982 from the dockerfile.

推荐答案

您可以将其作为构建参数传递.你的 Dockerfile 可以是静态的:

You can pass it as a build arg. Your Dockerfile can be static:

FROM ubuntu:xenial-20170214
ARG UNAME=testuser
ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o $UNAME
RUN useradd -m -u $UID -g $GID -o -s /bin/bash $UNAME
USER $UNAME
CMD /bin/bash

然后您将在构建命令中传递选项:

Then you'd pass the options on your build command:

docker build --build-arg UID=$(id -u) --build-arg GID=$(id -g) 
  -f bb.dockerfile -t testimg .

<小时>

请注意,我已经以不同的方式解决了与此类似的问题,方法是以 root 身份运行一个入口点,该入口点查看主机卷挂载的文件/目录权限,并调整容器内用户的 uid/gid 以匹配卷 uid/gid.进行该更改后,它会放弃从 root 用户到修改后的 uid/gid 用户的访问权限,并运行原始命令/入口点.结果是图像可以在任何开发人员机器上不加改变地运行.这方面的一个例子可以在我的 jenkins-docker 仓库中找到:


Note that I've solved similar problems to this a different way, by running an entrypoint as root that looks a file/directory permissions of the host volume mount, and adjust the uid/gid of the users inside the container to match the volume uid/gid. After making that change, it drops access from the root user to the modified uid/gid user and runs the original command/entrypoint. The result is the image can be run unchanged on any developer machine. An example of this can be found in my jenkins-docker repo:

https://github.com/sudo-bmitch/jenkins-docker

这篇关于Dockerfile 将主机用户 UID 和 GID 复制到镜像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆