首页 > 解决方案 > Docker 入口点用户切换

问题描述

我正在创建一个 docker 映像以用作其他应用程序的基础。要求是:

我创建了以下 Dockerfile

FROM node:14.15.1-alpine3.11

# Specify node/npm related envs
ENV NPM_CONFIG_LOGLEVEL=warn    \
    NO_UPDATE_NOTIFIER=1

# Change cwd for next commands
WORKDIR /home/node/code

# Set local registry
RUN echo "registry=http://192.168.100.175:4873" > /home/node/.npmrc && \
    chown -R node:node /home/node && \
    apk add --update --no-cache tzdata=2021a-r0 ca-certificates=20191127-r2 su-exec=0.2-r1

# Need root to update CA certificates in entrypoint.sh and then switch back to restricted user
USER root
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT [ "./entrypoint.sh" ]

# Execute the service entrypoint
CMD ["sh"]

entrypoint.sh

#!/bin/sh

DIR_CRT="/home/node/certificates"
if [ "$(ls -A ${DIR_CRT})" ]; then
  cp -r "${DIR_CRT}/." /usr/local/share/ca-certificates/
  update-ca-certificates
  echo "******* Updated CA certificates *******"
fi

exec su-exec node "$@"

这似乎满足了要求,但我注意到,如果我在图像中打开一个 shell,node即使我从参数中指定了一个不同的 shell,它也总是与用户在一起:

$ docker run --rm -it -u root docker.repo.asts.com/scc-2.0/app-tg:1.6.0-beta50 whoami
node

是否可以同时满足要求和与所需用户一起执行直接命令的可能性?

标签: dockerdockerfile

解决方案


docker run -u xxx仅当您未使用execinentrypoint更改 PID1 时才有效。例如

$ docker run --rm -it node:14.15.1-alpine3.11 whoami
root
$ docker run --rm -u node -it node:14.15.1-alpine3.11 whoami
node

使用后将exec su-exec node "$@"用户更改为node,您将无法-u xxx再次使用。唯一的解决方案是像下一个那样覆盖入口点,但我看不到这里的含义:

docker run --rm -u root --entrypoint=/bin/sh xxx

但是,您仍然可以在现有容器中使用docker exec -u rootdocker exec -u node获取该用户的外壳。


推荐阅读