我想创建一个带有 cmdline 可指定退出代码的 docker 映像。从这个问题中,我了解到我必须将exit
其用作参数,sh
因为它是 shell 内置命令,而不是可执行文件:How to make a docker container exit with a specific error-code with docker-compose?
即我可以创建一个以错误代码 42 退出的 docker 容器,如下所示:
# Dockerfile
FROM alpine:3.15 as base
ENTRYPOINT ["sh", "-c", "exit 42"]
$ docker build -t tmp:tmp . && docker run tmp:tmp
[+] Building 0.4s (5/5) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 181B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/alpine:3.15 0.0s
=> CACHED [1/1] FROM docker.io/library/alpine:3.15 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:3034115e85f4ac9322c3e3e5d69f4445e30cc652f3b836d0145545305fda6ad1 0.0s
=> => naming to docker.io/library/tmp:tmp 0.0s
$ echo $?
42
$
问题:
可以使 docker 容器返回指定为 cmdline 参数的退出代码吗?
例如,这可能吗:
$ docker build -t tmp:tmp . && docker run tmp:tmp 64
...
$ echo $?
64
$
?
我试过的:
这篇文章——https ://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/——让我尝试了ENTRYPOINT
和的这种组合CMD
:
# Dockerfile
FROM alpine:3.15 as base
ENTRYPOINT ["sh", "-c", "exit"]
CMD ["0"]
$ docker build -t tmp:tmp . && docker run tmp:tmp 64
...
$ echo $?
0
有趣的是,Dockerfile 的同样“模式”适用于echo
:
# Dockerfile
FROM alpine:3.15 as base
ENTRYPOINT ["echo", "hello"]
CMD ["world"]
$ docker build -t tmp:tmp . && docker run tmp:tmp
...
hello world
$
$ docker build -t tmp:tmp . && docker run tmp:tmp foo
...
hello foo
$
我认为我失败的实验ENTRYPOINT
并由CMD
这个实验解释:
$ sh -c "exit 42"
$ echo $?
42
$ sh -c "exit" 42
$ echo $?
0
...我希望我的 Dockerfile 与ENTRYPOINT ["sh", "-c", "exit"]
andCMD ["0"]
会导致前者,但我认为它会导致后者——真的吗?