Docker-compose external_links无法连接

Chr*_*ris 4 docker docker-compose

我有几个应用程序容器,我想连接到mongodb容器.我尝试使用external_links,但我无法连接到mongodb.

我明白了

MongoError:第一次连接时无法连接到服务器[mongodb:27017]

我是否必须将容器添加到同一网络中以使external_links正常工作?

MongoDB的:

version: '2'
services:
  mongodb:
    image: mongo:3.4
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - data:/data/db
volumes:
  data:
Run Code Online (Sandbox Code Playgroud)

应用程序:

version: '2'
services:
  app-dev:
    restart: Always
    build: repository/
    ports:
      - "3000:80"
    env_file:
      - ./environment.env
    external_links:
      - mongodb_mongodb_1:mongodb
Run Code Online (Sandbox Code Playgroud)

网络:

# sudo docker network ls
NETWORK ID          NAME                      DRIVER              SCOPE
29f8bae3e136        bridge                    bridge              local
67d5519cb2e6        dev_default               bridge              local
9e7097c844cf        host                      host                local
481ee4301f7c        mongodb_default           bridge              local
4275508449f6        none                      null                local
873a46298cd9        prod_default              bridge              local
Run Code Online (Sandbox Code Playgroud)

Yuv*_*uva 13

https://docs.docker.com/compose/compose-file/#/externallinks上的文档 说

If you’re using the version 2 file format, the externally-created containers must be connected to at least one of the same networks as the service which is linking to them.
Run Code Online (Sandbox Code Playgroud)

例如:

创建一个新的docker网络

docker network create -d bridge custom

搬运工-撰写-1.yml

    version: '2'

    services:
      postgres:
        image: postgres:latest
        ports:
          - 5432:5432
        networks:
          - custom

    networks:
      custom:
        external: true
Run Code Online (Sandbox Code Playgroud)

搬运工-撰写-2.yml

    version: '2'

    services:
      app:
        image: training/webapp
        networks:
          - custom
        external_links:
          - postgres:postgres

    networks:
      custom:
        external: true
Run Code Online (Sandbox Code Playgroud)

  • 根本无法意识到“external_links”需要什么?如果将两个 compose 添加到相同的网络,例如 docker-compose-1 和 docker-compose-2 都有“networks: {custom: {external: true}}”,则彼此定义的服务无需“external_links”即可通过其名称进行访问。它只是为了明确声明依赖关系吗? (3认同)

小智 5

Yuva 上面对第 2 版的回答也适用于第 3 版。

external_links 的文档不够清楚。

为了更清楚,我粘贴了带有注释的版本 3 变体

version: '3'

services:
  app:
    image: training/webapp
    networks:
      - <<network created by other compose file>>
    external_links:
      - postgres:postgres

networks:
  <<network created by other compose file>>:
    external: true
Run Code Online (Sandbox Code Playgroud)