为什么在 docker 容器内运行的命令不能通过 docker 运行 从外部运行?

Why doesn't a command that works inside a docker container work from outside via docker run?

我有一个名为 my_container 的容器,当我 运行 docker run -i -t my_container 我可以 运行 npm --version 然后我得到 2.7.4

然而,当我尝试使用 docker run --workdir=/home/ubuntu/www my_container npm --version 从容器外部 运行 相同的命令时,我收到一条错误消息:

Unable to locate npm. lxc-start: The container failed to start. lxcstart: Additional information can be obtained by setting the --logfile and --logpriority options.

我 运行 的大多数命令都具有相同的行为,而不仅仅是 npm。我在 Circle CI 中这样做,如果这能增加更多线索的话。

可能是因为容器的entrypoint是为了给你一个shell,而不带参数。可以使用docker inspect查看镜像入口

$ docker build -
FROM busybox
ENTRYPOINT ["/bin/sh"]
Sending build context to Docker daemon 2.048 kB
Sending build context to Docker daemon 
Step 0 : FROM busybox
 ---> 8c2e06607696
Step 1 : ENTRYPOINT /bin/sh
 ---> Running in eb5b4d32af96
 ---> ad1286aebbe2
Removing intermediate container eb5b4d32af96
Successfully built ad1286aebbe2

13:59 ~ $ docker run --rm -ti ad1286aebbe2 echo hi
/bin/sh: can't open 'echo'

busybox 官方没有入口点,因此参数被视为命令,这意味着它们直接进入 /bin/sh -c.