docker-compose:网络和链接之间的区别 [英] docker-compose: difference between networks and links
问题描述
我正在学习 docker.我看到这两个术语让我感到困惑.例如,这里是一个 docker-compose,它定义了两个服务 redis
和 web-app
.
I'm learning docker. I see those two terms make me confuse. For example here is a docker-compose that defined two services redis
and web-app
.
services:
redis:
container_name: redis
image: redis:latest
ports:
- "6379:6379"
networks:
- lognet
app:
container_name: web-app
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
volumes:
- ".:/webapp"
links:
- redis
networks:
- lognet
networks:
lognet:
driver: bridge
这个 docker-compose
文件定义了一个名为 lognet 的桥接网络,所有服务都将连接到这个网络.据我了解,此操作使那些服务可以看到其他服务.那么为什么在上述情况下应用服务仍然需要链接到redis服务.
This docker-compose
file defines a bridge network named lognet and all services will connect to this network. As I understand, this action makes those services can see others. So why app service still need to link to redis service in above case.
谢谢
推荐答案
链接已被网络取代.Docker 将它们描述为您应该避免使用的遗留功能.您可以安全地删除链接,两个容器将能够通过它们的服务名称(或 container_name)相互引用.
Links have been replaced by networks. Docker describes them as a legacy feature that you should avoid using. You can safely remove the link and the two containers will be able to refer to each other by their service name (or container_name).
使用撰写,链接确实具有创建隐含依赖项的副作用.您应该将其替换为更明确的 depends_on部分,以便应用不会在 redis 启动之前或之前尝试运行.
With compose, links do have a side effect of creating an implied dependency. You should replace this with a more explicit depends_on section so that the app doesn't attempt to run without or before redis starts.
顺便说一句,我不是硬编码 container_name 的粉丝,除非您确定这是主机上唯一具有该名称的容器,并且您需要从 docker cli 按名称引用它.如果没有容器名称,docker-compose 会给它一个不太直观的名称,但它也会给它一个网络上的 redis 别名,这正是容器到容器网络所需要的.因此,这些建议的最终结果是:
As an aside, I'm not a fan of hard coding container_name unless you are certain that this is the only container that will exist with that name on the host and you need to refer to it from the docker cli by name. Without the container name, docker-compose will give it a less intuitive name, but it will also give it an alias of redis on the network, which is exactly what you need for container to container networking. So the end result with these suggestions is:
version: '2'
# do not forget the version line, this file syntax is invalid without it
services:
redis:
image: redis:latest
ports:
- "6379:6379"
networks:
- lognet
app:
container_name: web-app
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
volumes:
- ".:/webapp"
depends_on:
- redis
networks:
- lognet
networks:
lognet:
driver: bridge
这篇关于docker-compose:网络和链接之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!