无法从 docker 连接到 mongodb 实例:连接被拒绝

Sou*_*aji 2 mongodb pymongo mongokit docker docker-compose

我正在使用 docker-compose 创建一个多容器环境,其中我有一个 mongodb 实例和两个 python 应用程序。问题是,第一个应用程序能够建立到 mongodb 的连接,而第二个应用程序失败并出现以下错误:

File "/usr/local/lib/python2.7/site-packages/pymongo/mongo_client.py", 
            line 377, in __init__ notification_1   | 
            raise ConnectionFailure(str(e)) notification_1   | 
            pymongo.errors.ConnectionFailure: [Errno -2] Name or service not known
Run Code Online (Sandbox Code Playgroud)

我的项目结构:

.
??? docker-compose.yml
??? form
?   ??? app.py
?   ??? Dockerfile
?   ??? requirements.txt
?   ??? static
?   ??? templates
?       ??? form_action.html
?       ??? form_sumbit.html
??? notify
?   ??? app.py
?   ??? Dockerfile
?   ??? requirements.txt
??? README
Run Code Online (Sandbox Code Playgroud)

这是我的[更新] docker-compose.yml 文件:

version: '3'

services:
  db:
    image: mongo:3.0.2
    container_name: mongo
    networks:
      db_net:
        ipv4_address: 172.16.1.1


  web:
    build: form
    command: python -u app.py
    ports:
      - "5000:5000"
    volumes:
      - form:/form
    environment:
      MONGODB_HOST: 172.16.1.1
    networks:
      db_net:
        ipv4_address: 172.16.1.2

  notification:
    build: notify
    command: python -u app.py
    volumes:
      - notify:/notify
    environment:
      MONGODB_HOST: 172.16.1.1
    networks:
      db_net:
        ipv4_address: 172.16.1.3

networks:
  db_net:
    external: true

volumes:
  form:   
  notify:
Run Code Online (Sandbox Code Playgroud)

第一个应用基于 Flask,使用 mongokit 连接数据库。下面是建立连接的代码:

MONGODB_HOST = os.environ['DB_PORT_27017_TCP_ADDR']
MONGODB_PORT = 27017

app = Flask(__name__)
app.config.from_object(__name__)

# connect to the database
try:
    connection = Connection(app.config['MONGODB_HOST'], app.config['MONGODB_PORT'])
except ConnectionFailure:
    print("Connection to db failed. Start MongoDB instance.")
    sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

第二个应用程序是一个简单的 Python 应用程序。连接的代码如下:

MONGODB_HOST = os.environ['DB_PORT_27017_TCP_ADDR']
MONGODB_PORT = 27017
connection = Connection(MONGODB_HOST, MONGODB_PORT)
Run Code Online (Sandbox Code Playgroud)

Kin*_*ang 5

是否有理由为所有服务明确指定 IP 地址,以及 db 服务的容器名称?我建议删除它们并使用服务名称在同一网络上的容器之间进行连接。

version: '3'

services:
  db:
    image: mongo:3.0.2
    networks:
      - db_net

  web:
    build: form
    command: python -u app.py
    ports:
      - "5000:5000"
    volumes:
      - form:/form
    environment:
      MONGODB_HOST: db
    networks:
      - db_net

  notification:
    build: notify
    command: python -u app.py
    volumes:
      - notify:/notify
    environment:
      MONGODB_HOST: db
    networks:
      - db_net

networks:
  db_net:

volumes:
  form:   
  notify:
Run Code Online (Sandbox Code Playgroud)