如何用docker-compose让一个带有特定错误代码的docker容器退出?如何用、容器、错误代码、compose

2023-09-03 14:25:45 作者:难遇

我可以用docker-compose启动一个Docker容器,并用这个例子检查它的退出代码:

# Dockerfile
FROM alpine:3.15 as base
# docker-compose.yml
version: '3.6'
services:
  dummy:
    build:
      context: .
    entrypoint: ["sleep", "42"]
    image: "tmp:tmp"
$ docker-compose up --force-recreate
WARNING: The Docker Engine you're using is running in swarm mode.

Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled on the current node.

To deploy your application across the swarm, use `docker stack deploy`.

Recreating docker-compose_dummy_1 ... done
Attaching to docker-compose_dummy_1
docker-compose_dummy_1 exited with code 0
$ docker inspect docker-compose_dummy_1 --format='{{.State.ExitCode}}' # 42 seconds later
0

是否可以使用特定错误代码退出此容器? 我希望docker inspect的结果返回可在docker-compose.yml中指定的非零值。

记一次神奇的docker compose访问网络不通问题

我天真地认为将入口点从sleep更改为exit应该有效:

# docker-compose.yml
version: '3.6'
services:
  dummy:
    build:
      context: .
    entrypoint: ["exit", "42"]
    image: "tmp:tmp"

...但它没有:

$ docker-compose up --force-recreate
WARNING: The Docker Engine you're using is running in swarm mode.

Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled on the current node.

To deploy your application across the swarm, use `docker stack deploy`.

Recreating docker-compose_dummy_1 ... error

ERROR: for docker-compose_dummy_1  Cannot start service dummy: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "exit": executable file not found in $PATH": unknown

ERROR: for dummy  Cannot start service dummy: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "exit": executable file not found in $PATH": unknown
ERROR: Encountered errors while bringing up the project.

推荐答案

更仔细地查看错误消息:

ERROR: for docker-compose_dummy_1  Cannot start service dummy: OCI
runtime create failed: container_linux.go:345: starting container
process caused "exec: "exit": executable file not found in $PATH":
unknown

当您指定像["exit", "42"]这样的入口点时,它不会在外壳中执行。Docker正在您的$PATH中查找名为exit的命令,当然不存在此类命令。

您需要在外壳中运行命令,因为exit是外壳命令:

    entrypoint: ["/bin/sh", "-c", "exit 42"]
 
精彩推荐
图片推荐