docker-compose:网络与链接之间的区别 [英] docker-compose: difference between network and link

查看:267
本文介绍了docker-compose:网络与链接之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习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 部分,以便该应用不会

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆