当在 Docker 容器中切换用户遇到问题时,以下是常见原因和解决方案:
错误表现:su: user 'username' does not exist
或 whoami: cannot find name for user ID XXXX
解决方法:
# 在Dockerfile中添加用户
RUN useradd -ms /bin/bash username
错误表现:su: command not found
解决方法:
# 在Dockerfile中安装必要的软件包
RUN apt-get update && apt-get install -y sudo
错误表现:权限被拒绝或操作不被允许
解决方法:
# 使用USER指令前确保有足够权限
USER root
# 执行需要权限的操作
RUN chown username:username /some/directory
USER username
错误表现:su: Authentication failure
解决方法:
# 为用户设置密码
RUN echo "username:password" | chpasswd
RUN groupadd -r username && useradd -r -g username username
USER username
RUN curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/1.4/gosu-$(dpkg --print-architecture)" \
&& chmod +x /usr/local/bin/gosu
docker run --user username image_name
cat /etc/passwd | grep username
# 检查用户ID和组ID
id username
# 检查可用的shell
cat /etc/shells
# 在Dockerfile中
ARG USER_ID=1000
ARG GROUP_ID=1000
RUN groupadd -g ${GROUP_ID} username && \
useradd -l -u ${USER_ID} -g username username
#!/bin/sh
if [ "$(id -u)" = "0" ]; then
exec gosu username "$@"
fi
exec "$@"
通过以上方法,您应该能够解决Docker容器中切换用户失败的问题。根据具体错误信息选择相应的解决方案。