无法在 docker Alpine 中添加具有高 UID 的用户

Can't add a user with a high UID in docker Alpine

我正在尝试在 Alpine Linux Docker 容器中使用 UID 1340816314 创建一个新用户,以便让用户具有 UID 匹配主机上的特定用户。

问题是,即使我按照 adduser man page. I don't think by the way that it has any impact as the adduser command in Alpine .

/etc/login.defs 中重新定义 UID_MAX 的值,我仍然面临 adduser: number 1340816314 is not in 0..256000 range

这是我尝试执行的操作的日志:

$ docker run -it --rm alpine:3.4 sh
/ # adduser -D -g '' -u 1340816314 user
adduser: number 1340816314 is not in 0..256000 range
/ # echo "UID_MAX 1340816314" > /etc/login.defs
/ # adduser -D -g '' -u 1340816314 user
adduser: number 1340816314 is not in 0..256000 range
/ # echo "UID_MAX 1340816315" > /etc/login.defs
/ # adduser -D -g '' -u 1340816314 user
adduser: number 1340816314 is not in 0..256000 range

您知道如何在 Docker 容器内的 Alpine Linux 中添加具有大 UID 的用户吗?

这是一个有效但肮脏的解决方法,通过手动创建用户,使用 $UID_TO_SET 作为 bash 包含要设置的高 UID 的变量:

# Create user
echo "user:x:$UID_TO_SET:$UID_TO_SET::/home/user:" >> /etc/passwd
## thanks for  to compute the creation date
echo "user:!:$(($(date +%s) / 60 / 60 / 24)):0:99999:7:::" >> /etc/shadow
echo "user:x:$UID_TO_SET:" >> /etc/group
mkdir /home/user && chown user: /home/user

在 Alpine 中有一个更优雅的解决方案 UID/GID UID/GID。

shadow contains useraddgroupadd 实用程序反过来支持更高的值。不确定这些实用程序的上限是多少,是否支持整个 2^32 space,但我已经用超过 6 亿的值进行了测试并且它有效。

例如,实现此目的的命令如下所示:

UID=666000666
GID=999000999
apk add shadow
/usr/sbin/groupadd -g ${GID} my_group
/usr/sbin/useradd -s /bin/sh -g ${GID} -u ${UID} my_user

请注意,我将 shell 变量传递给 useradd,因为默认情况下它会尝试使用未安装的 /bin/bash

这个问题实际上启发了我以某种方式解决它,这种方式对于获取长 ID 以在基于 Docker 图像的 Alpine 和 BusyBox 上工作的特定用例来说既方便又易于使用。

https://github.com/theAkito/userdef

用法示例:

## Get the binary.
## The default Docker Tag provides the Alpine (musl) based binary.
FROM akito13/userdef AS base
## Pull the image you want to modify the executing user of.
FROM gitea/gitea:1.16.5-linux-amd64-rootless

## We temporarily need to use the root user,
## as we are doing administrative tasks, like e.g. modifying an OS user.
USER root:root
COPY --from=base /userdef /userdef
## 1. Change the existing user.
## 2. Use that user to `chown` relevant folders.
## 3. Remove the binary, because the user has been changed,
##    i.e. our job is done here.
RUN /userdef -h=/var/lib/gitea/git -n=git -u=9234 -g=9234 && \
  chown git:git -R /var/lib/gitea /etc/gitea && \
  rm -f /userdef

## Switch to the now relevant executing user.
USER 9234:9234
## Taken from https://github.com/go-gitea/gitea/blob/66f2210feca0b50d305a46a203c2b3d2f4d3790b/Dockerfile.rootless#L71-L72
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
CMD []