当外部链接的容器实际上使用docker-compose运行时,如何避免“Docker无法链接到非运行容器”错误

我们想要做什么:

我们希望使用docker-compose将一个已经运行的容器(A) 通过容器名称链接到另一个容器(B)。 我们使用“ external-link ”,因为两个容器都是从不同的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 

示例代码:

docker-compose.yml容器B

 container_b: external_links: - container_a_1 

与其他“如何解决”这个问题有什么不同? – 问题:

  • 我们不能使用“sudo服务docker重启”(工作),因为这是一个生产环境
  • 我们不想每次都手动修复这个问题但find原因是我们可以做到的
    • 明白我们做错了什么
    • 了解如何避免这一点

假设:

  • 看起来像container_a的两个实例存在(RUNNING_ID和PREVIOUSLY_LINKED_ID)
  • 这可能是因为我们
    • 通过docker-compose构build和重build容器
    • 更改了容器的转发外部端口(808 0 1 :8080)

评论

  • 不要像评论中所build议的那样使用docker-compose down ,这样就可以删除文件了!

Docker链接已经被弃用,所以除非你需要一些他们提供的function,或者是一个非常老的Docker版本,我build议你切换到dockernetworking。

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

 docker network create app_net 

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

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

然后在container_b中,将连接到container_a作为“container_a”,而不是“container_a_1”。

docker-compose down一下,除非你传递了-v标志,否则docker-compose down将不会logging删除卷。 也许你正在使用匿名卷,在这种情况下,我不确定docker-compose up会知道在哪里find你的数据。 一个命名的卷是首选。 您的数据很可能没有存储在卷中,这很危险,并且会消除您更新容器的能力:

 $ 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