一尘不染

mongod --bind_ip使用docker-compose版本2

docker

我正在尝试使用来连接在docker上运行的两个mongodb容器docker- compose。一个容器使用将种子中的数据提供给另一个容器mongoimport

但是,运行时出现以下错误 mongoimport

Failed: error connecting to db server: no reachable servers

实际上,我可以mongodb从到达容器,mongo-seed因为我将追加了ping -c 3 mongodbCMD并且容器可以成功解析该主机名。

在我正在使用的文件下面:

docker-compose.yml

version: '2'

services:
  mongodb:
    image: mongo:3.2
    ports:
      - "27017:27017"

  mongo-seed:
    build: ./mongo-seed

mongo-seed / Dockerfile

FROM mongo:3.2

COPY init.json /init.json
CMD ping -c 3 mongodb && mongoimport --host mongodb --db test --collection users \
   --type json --file /init.json --jsonArray

mongo-seed / init.json

[
  {
    "name": "Joe Smith",
    "email": "jsmith@gmail.com",
    "age": 40,
    "admin": false
  },
  {
    "name": "Jen Ford",
    "email": "jford@gmail.com",
    "age": 45,
    "admin": true
  }
]

这是输出docker-compose up

mongo-seed_1  | PING mongodb (172.18.0.2): 48 data bytes
mongo-seed_1  | 56 bytes from 172.18.0.2: icmp_seq=0 ttl=64 time=0.116 ms
mongo-seed_1  | 56 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.141 ms
mongo-seed_1  | 56 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.114 ms
mongo-seed_1  | --- mongodb ping statistics ---
mongo-seed_1  | 3 packets transmitted, 3 packets received, 0% packet loss
mongo-seed_1  | round-trip min/avg/max/stddev = 0.114/0.124/0.141/0.000 ms
mongo-seed_1  | 2016-08-09T20:34:15.728+0000    [........................] smtt.devices 0.0 B/25.5 MB (0.0%)
mongo-seed_1  | 2016-08-09T20:34:17.992+0000    [........................] smtt.devices 0.0 B/25.5 MB (0.0%)
mongo-seed_1  | 2016-08-09T20:34:17.992+0000    Failed: error connecting to db server: no reachable servers
mongo-seed_1  | 2016-08-09T20:34:17.992+0000    imported 0 documents
mongo_mongo-seed_1 exited with code 1

任何的想法?我想念什么?


阅读 617

收藏
2020-06-17

共1个答案

一尘不染

我终于可以设法连接两个容器。我的发现是出于文档目的。

要点

  • docker-compose版本2创建bridge网络并向其中添加所有容器。
  • mongod不知道此网络,因此未绑定到该IP。默认情况下,仅绑定到127.0.0.1
  • mongoimport 即使应该将其转换为容器ip,也无法使用容器名称建立连接。

  • 通过显式定义为mongodb分配静态IP network
  • 初始化mongo容器,其--bind_ip标志指向该静态ip
  • 使用IP地址代替主机名 mongoimport

docker-compose.yml

version: '2'

services:
  mongodb:
    image: mongo:3.2
    ports:
      - "27017:27017"
    networks:
      mongo_net:
        ipv4_address: 172.16.0.1
    command: mongod --bind_ip 127.0.0.1,172.16.0.1

  mongo-seed:
    build: ./mongo-seed
    networks:
      mongo_net:
    depends_on:
      - mongodb

networks:
  mongo_net:
    driver: bridge
    ipam:
      config:
      - subnet: 172.16.0.0/24
        gateway: 172.16.0.254

mongo-seed / Dockerfile

FROM mongo:3.2

COPY init.json /init.json
CMD mongoimport --host 172.16.0.1 --db test --collection users \
   --type json --file /init.json --jsonArray
2020-06-17