如何通过主机之一连接2个Docker容器?

时间:2019-10-29 05:31:32

标签: docker-compose

我将nginx代理容器作为主机,并希望通过localhost在cms和mongo容器之间进行通信。不幸的是,无法从cms容器获得localhost:27017。

我该如何根据需要连接它们?

docker-compose配置是下一个:

version: '3'
services:
  proxy:
    image: nginx:1.15-alpine
    restart: unless-stopped
    privileged: true
    ports:
      - "80:80"
      - "443:443"
    network_mode: host
    depends_on:
      - cms
      - mongo
  cms:
    container_name: cms
    restart: unless-stopped
    build: cms
    env_file:
    links:
      - mongo
    ports:
      - '1337:1337'
  mongo:
    image: mongo
    restart: always
    ports:
      - '27017:27017'
  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081

顺便说一句:mongo-express可以访问mongo容器

1 个答案:

答案 0 :(得分:1)

  • 尝试使用其服务名称mongo连接到cms中的mongo:27017

或将network_mode: host添加到mongo服务规范:

  mongo:
    image: mongo
    restart: always
    network_mode: host
    ports:
      - '27017:27017'

和cms:

  cms:
    container_name: cms
    restart: unless-stopped
    build: cms
    network_mode: host
    env_file:
    links:
      - mongo
    ports:
      - '1337:1337'

如果您想使用localhost:27017中的cms连接到mongo