docker - docker_compose.yml 中的 links 和 depends_on 的区别

标签 docker docker-compose dockerfile

根据 Docker Compose 的 compose-file documentation :

  • depends_on - 表达服务之间的依赖关系。
  • links - 链接到另一个服务中的容器,并以与 depends_on 相同的方式表达服务之间的依赖关系 .

我不明白链接到其他容器的目的,所以两个选项之间的区别对我来说似乎仍然相当困难。

如果有例子会容易得多,但我找不到任何例子。

我注意到,当我将容器 B 与容器 A 链接时,容器 B 将在容器 A 的外壳内“可ping”。

我在容器A的bash中运行ping B得到了这样的结果(仅供引用,图片来自互联网)

enter image description here

最佳答案

此答案适用于 docker-compose version 2,它也适用于 version 3

您仍然可以在使用 depends_on 时访问数据。

如果您查看 docker 文档 Docker Compose and Django ,您仍然可以像这样访问数据库:

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

links和depends_on有什么区别?

链接:

为数据库创建容器时,例如:

docker run -d --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" -P mysql

docker inspect d54cf8a0fb98 |grep HostPort

你可能会发现

"HostPort": "32777"

这意味着您可以从本地主机端口 32777(容器中的 3306)连接数据库,但每次重新启动或删除容器时,此端口都会更改。因此,您可以使用链接来确保始终连接到数据库,而不必知道它是哪个端口。

web:
  links:
   - db

取决于:

我从 Giorgio Ferraris Docker-compose.yml: from V1 to V2 找到了一个不错的博客

When docker-compose executes V2 files, it will automatically build a network between all of the containers defined in the file, and every container will be immediately able to refer to the others just using the names defined in the docker-compose.yml file.

So we don’t need links anymore; links were used to start a network communication between our db container and our web-server container, but this is already done by docker-compose

更新

depends_on

表达服务之间的依赖关系,有两个作用:

  • docker-compose up 将按依赖顺序启动服务。在下面的例子中,db 和 redis 将在 web 之前启动。
  • docker-compose up SERVICE 会自动包含 SERVICE 的依赖。在下面的例子中,docker-compose up web 也会创建并启动 db 和 redis。

简单示例:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

Note: depends_on will not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

关于docker - docker_compose.yml 中的 links 和 depends_on 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832095/

相关文章:

linux - 第三个远程服务器中的 Bash 变量

git - docker :git clone结果不在本地卷中,args不扩展

docker - 如何使用主机网络进行docker compose?

docker - 如何在 Openshift 上运行 Arangodb?

bash - 如何在 Dockerfile 中设置 .bash_profile 环境变量?

linux - docker-compose 错误 这是什么?

macos - 如何在Mac上使用Docker进行调试

Docker:当 Dockerfile 位于子目录中时使用 COPY

bash - 检查非守护进程 Docker 容器,在它完成运行后

docker - 访问容器从Azure VSTS上的Hosted Linux Agent从Docker Compose步骤启动