【问题标题】:How to execute one command as root, another command as different user in one RUN statement如何在一个 RUN 语句中以 root 身份执行一个命令,以不同用户身份执行另一个命令
【发布时间】:2021-10-07 12:25:17
【问题描述】:

在构建映像时,我需要以 root 身份执行一些命令,并以不同用户身份执行一些命令。所有命令都应在一个 RUN 语句内执行,以保留由第一个命令创建的后台服务。我试过了:

USER root     
RUN sudo -i -u postgres "pg_ctl -w start" \
  && cd /home/backend && npm run server & sleep 50 \
  && cd /home/frontend && npm run test

它给了我错误:

-bash: pg_ctl -w start: command not found
The command '/bin/sh -c sudo -i -u postgres "pg_ctl -w start"   && cd /home/backend && npm run server & sleep 50 && cd /home/frontend && npm run test' returned a non-zero code: 127

如果我这样做:

USER postgres
RUN pg_ctl -w start \
  && cd /home/backend && npm run server & sleep 50 \
  && cd /home/frontend && npm run test

一切正常。那么,之前的代码有什么问题呢?

Dockerfile 是从基于 Debian 9 的 node:12.18.0 创建的。

【问题讨论】:

  • 这似乎是您尝试在 Dockerfile 中运行多容器集成测试。我根本不会这样做。使用 Docker Compose 之类的工具启动数据库和后端容器,然后从 Docker 外部的主机系统运行 npm run test 以启动测试。
  • @DavidMaze 非常感谢这个建议。我想我可以在 docker compose 中运行具有入口点sleep 50 && npm run test 的后端、数据库容器和测试容器。然后做docker-compose up --abort-on-container-exit

标签: linux docker dockerfile sudo docker-build


【解决方案1】:

去掉引号,可执行文件是pg_ctl而不是pg_ctl -w start

RUN sudo -i -u postgres pg_ctl -w start \

之前的代码有什么问题?

就像你会做的一样:

RUN "pg_ctl -w start" \

【讨论】:

  • 去掉引号后显示-bash: pg_ctl: command not found
  • 那么pg_ctl 不在PATH 中。检查type pg_ctlwhich pg_ctl 的输出并将路径添加到PATH 以使用可执行文件的完整路径。
  • 我只是不明白为什么在使用USER postgresRUN pg_ctl -w start时它在PATH中,但在使用RUN sudo -i -u postgres pg_ctl -w start时却不在PATH
猜你喜欢
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多