当外部链接的容器实际运行时,如何使用 docker-compose 避免"Docker cannot link to a non running container"错误



我们想要做的事情:

我们希望使用docker compose通过容器名称将一个已经运行的容器(A)链接到另一个容器(B)。我们使用">外部链接",因为两个容器都是从不同的docker-compose.yml文件启动的。

问题:

容器B未能以错误启动,尽管具有该名称的容器正在运行。

ERROR: for container_b  Cannot start service container_b: Cannot link to a non running container: /PREVIOUSLY_LINKED_ID_container_a_1 AS /container_b_1/container_a_1

"docker ps"的输出

CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                         NAMES
RUNNING_ID        container_a       "/docker-entrypoint.s"   15 minutes ago      Up 15 minutes       5432/tcp                      container_a_1

示例代码:

容器B的docker-compose.yml

container_b:
external_links:
- container_a_1

此问题与其他"如何修复"问题的区别:

  • 我们不能使用"sudoservicedockerrestart"(有效),因为这是一个生产环境
  • 我们不想每次手动都解决这个问题,但要找到原因,这样我们就可以
    • 了解我们做错了什么
    • 了解如何避免这种情况

假设:

  • 似乎存在container_a的两个实例(RUNNING_ID和PREVIOSLY_LINKED_ID)
  • 这可能是因为我们
    • 通过docker compose build和
    • 更改了容器的转发外部端口(80801:8080)

注释

  • 不要按照评论中的建议使用docker-compose down,这会删除卷

Docker链接已被弃用,因此除非您需要它们提供的某些功能,或者使用的是非常旧的Docker版本,否则我建议您切换到Docker网络。

由于您想要连接的容器似乎是在单独的组合文件中启动的,因此您可以从外部创建该网络:

docker network create app_net

然后在docker-compose.yml文件中,将容器连接到该网络:

version: '3'
networks:
app_net:
external:
name: app_net
services:
container_a:
# ...
networks:
- app_net

然后在您的container_b中,您将以"container_a"而不是"container_a_1"的身份连接到container_a。

顺便说一句,除非传递-v标志,否则docker-compose down不会被记录为删除卷。也许您使用的是匿名卷,在这种情况下,我不确定docker-compose up是否知道在哪里可以找到您的数据。首选命名卷。更有可能的是,你的数据没有存储在一个卷中,这是危险的,并使你无法更新你的容器:

$ docker-compose down --help
By default, the only things removed are:
- Containers for services defined in the Compose file
- Networks defined in the `networks` section of the Compose file
- The default network, if one is used
Networks and volumes defined as `external` are never removed.
Usage: down [options]
Options:
--rmi type          Remove images. Type must be one of:
'all': Remove all images used by any service.
'local': Remove only images that don't have a custom tag
set by the `image` field.
-v, --volumes       Remove named volumes declared in the `volumes` section
of the Compose file and anonymous volumes
attached to containers.
--remove-orphans    Remove containers for services not defined in the
Compose file

相关内容

最新更新