2016-12-07 91 views
2

我有几个应用程序容器,我想连接到MongoDB容器。我尝试了external_links,但我无法连接到MongoDB。Docker-compose external_links无法连接

我得到

MongoError: failed to connect to server [mongodb:27017] on first connect

我必须容器加入到同一个网络得到external_links工作?

的MongoDB:

version: '2' 
services: 
    mongodb: 
    image: mongo:3.4 
    restart: always 
    ports: 
     - "27017:27017" 
    volumes: 
     - data:/data/db 
volumes: 
    data: 

应用:

version: '2' 
services: 
    app-dev: 
    restart: Always 
    build: repository/ 
    ports: 
     - "3000:80" 
    env_file: 
     - ./environment.env 
    external_links: 
     - mongodb_mongodb_1:mongodb 

网络:

# 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 

回答

7

文档在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. 

例:

创建一个新的泊坞窗网络

docker network create -d bridge custom

泊坞窗,撰写-1.yml

version: '2' 

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

    networks: 
     custom: 
     external: true 

泊坞窗,撰写,2.yml

version: '2' 

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

    networks: 
     custom: 
     external: true 
+0

喜版本3的变化。你能给我一个关于如何将它们连接到同一网络的例子吗? – Chris

+0

解决了我的问题。真棒回答@yuva。与版本3一起工作。 – EnchanterIO

1

Yuva的第2版以上的答案也适用于第3版。

external_links的文档不够清晰。

为了更清楚我贴上了标注

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