2016-12-07 90 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