"usermod:UID'0'已经存在"为什么?

Rey*_*rPM 1 linux bash docker

作为我的Docker镜像的一部分,我有以下ENTRYPOINT脚本:

#!/bin/bash
set -e

if [ -z "${UID}" ]; then
    uid=1000;
else
    uid=${UID};
fi

if [ -z "${GID}" ]; then
    gid=1000;
else
    gid=${GID};
fi

echo "UID: $uid"
echo "GID: $gid"

data_dir="/var/www/html"
usermod -u "$uid" www-data && groupmod -g "$gid" www-data
chown -R www-data:root "$data_dir"

if  [ -d "$data_dir" ]; then
    chgrp -RH www-data "$data_dir"
    chmod -R g+w "$data_dir"
    find "$data_dir" -type d -exec chmod 2775 {} +
    find "$data_dir" -type f -exec chmod ug+rw {} +
fi

composer_cache_dir="/var/www/.composer"
mkdir -p "$composer_cache_dir"
chown -R www-data:root "$composer_cache_dir"

if  [ -d "$composer_cache_dir" ]; then
    chgrp -R www-data "$composer_cache_dir"
    chmod -R g+w "$composer_cache_dir"
fi

a2enmod rewrite expires

rm -f /var/run/apache2/apache2.pid

source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND "$@"
Run Code Online (Sandbox Code Playgroud)

图像编译成功.当我尝试通过运行以下命令来运行容器时,docker run -it temp bash我得到以下输出:

UID: 0
GID: 1000
usermod: UID '0' already exists
Enabling module rewrite.
Enabling module expires.
To activate the new configuration, you need to run:
  service apache2 restart
AH00112: Warning: DocumentRoot [/var/www/html/public_html] does not exist
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
Run Code Online (Sandbox Code Playgroud)

为什么我UID0?我找不到我的错误在哪里,任何帮助都非常受欢迎.

更新:

在脚本上更改以下行:

if [ "$UID" != 0 ]; then
    uid=1000;
else
    uid=${UID};
fi
Run Code Online (Sandbox Code Playgroud)

仍然要分配0uid,是因为var名称?(我使用了重建图像,docker build --no-cache -t temp .因此没有使用缓存)

ilk*_*chu 5

因为$UID在Bash中扩展到shell的当前用户id,并且它永远不会为空,所以[ -z "${UID}" ]永远不会是真的.所以,您正在设置uid=${UID};,可能uid=0是脚本以root身份运行.

然后usermod -u 0 www-data抱怨,因为它试图将UID更改www-data为零,但是已经在使用,并且没有-o标志就不会这样做.(而且你永远不想这样做......)

如果要测试if $UID是否为零,请使用[ "$UID" == 0 ].或者[[ $UID == 0 ]]在Bash.或者[ "$UID" -eq 0 ]进行数字比较,并不重要.

(我不确定www-data在任何情况下将uid更改为1000都是个好主意,你必须让用户usermod能够更改它的uid.但这不是问题.)

击:

UID
扩展为当前用户的用户标识,在shell启动时初始化.这个变量是只读的.

usermod命令:

-u, --uid UID
用户ID的新数值.
除非使用-o选项,否则此值必须是唯一的.该值必须是非负的.