如何知道由 `docker-compose up` 启动的所有容器的名称?

How to know the names of all containers spun up by `docker-compose up`?

我的任务是创建一个实用程序来启动 docker 个容器——通过调用 docker-compose up --detach——然后检查所有这些容器的退出代码。

我开始手动执行我认为实用程序会执行的操作,并使用非常简单的 Dockerfile 和 docker-compose.yml 示例:

我的Dockerfile和docker-compose.yml如下:

# Dockerfile
FROM alpine:3.15 as base
# docker-compose.yml
version: '3.6'
services:
  dummy:
    build:
      context: .
    entrypoint: ["sh", "-c", "exit 42"]
$ docker-compose up --build --detach
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`.

Building dummy
[+] Building 0.3s (5/5) FINISHED
 => [internal] load build definition from Dockerfile                                          0.0s
 => => transferring dockerfile: 43B                                                           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:35e223a20dbce8c0b81d3257f8cad0c7b2b35d8e18eadfec7eeb7de86a472e7b  0.0s
 => => naming to docker.io/library/docker-compose_dummy                                       0.0s
Successfully built 35e223a20dbce8c0b81d3257f8cad0c7b2b35d8e18eadfec7eeb7de86a472e7b
Starting docker-compose_dummy_1 ... done
$
$ docker inspect docker-compose_dummy_1 --format='{{.State.ExitCode}}'
42
$

问题:有没有办法知道 docker-compose up 启动的所有容器的名称,这似乎是后续 docker inspect 所需要的?
注意:我的实用程序可以设置环境变量,但它不能创建或修改 .env 或 docker-compose.yml.

根据最近的阅读 (docker-compose image named: "prefix_%s_1" instead of "%s"),我了解到服务的“前缀”可以用 --project-name 控制,默认为 basename $PWD

而从Docker-compose: why does the number appended to services not increment?,我了解到后缀数字随着--scale递增。

但我很难将所有这些组合成一个整体:所以给定一个不可变的 docker-compose.ymlDockerfile.env,我有什么办法可以确定由 docker-compose up --detach 启动的所有容器的名称,然后我可以使用 docker inspect ... --format='{{.State.ExitCode}}' 来确定每个容器的退出代码?

(我最不确定那个带后缀的整数。我认为我的实用程序不会使用 --scale 参数,但我不确定是否有其他原因导致后缀数字可能是除了“_1”之外的任何内容,所以我怀疑后缀是否为“_1”)

你试过了吗?

docker-compose ps -a