两个docker容器无法通信

zoe*_*vas 0 docker microservices dockerfile docker-compose

我有两个码头集装箱。一个容器是数据库,另一个是 Web 应用程序。Web 应用程序通过此链接 http://localhost:7200 调用数据库。但是,Web 应用程序 docker 容器无法到达数据库容器。

我试过这个 docker-compose.yml,但不起作用:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: 
       context: .
       dockerfile: ./docker/web/Dockerfile
    links:
      - graph-db
    depends_on:
     - graph-db
    ports:
     - "8080:8080"
    environment:
      - WAIT_HOSTS=graph-db:7200
    networks: 
      - backend

  graph-db:
    # will build ./docker/graph-db/Dockerfile
    build:
        ./docker/graph-db
    hostname: graph-db
    ports:
      - "7200:7200"

networks:
  backend:
    driver: "bridge"
Run Code Online (Sandbox Code Playgroud)

所以我有两个容器: Web 应用程序:http://localhost:8080/reasoner,这个容器调用位于不同容器中的 http://localhost:7200 中的数据库。但是,Web 容器无法访问数据库容器。

解决方案

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: 
       context: .
       dockerfile: ./docker/web/Dockerfile
    depends_on:
     - graph-db
    ports:
     - "8080:8080"
    environment:
      - WAIT_HOSTS=graph-db:7200


  graph-db:
    # will build ./docker/graph-db/Dockerfile
    build:
        ./docker/graph-db
    ports:
      - "7200:7200"
Run Code Online (Sandbox Code Playgroud)

并将 Web 应用程序代码中的 http://localhost:7200 替换为 http://graph-db:7200

BMi*_*tch 5

不要使用 localhost 在容器之间进行通信。网络是 docker 中的命名空间之一,因此容器内的 localhost 仅连接到该容器,而不连接到外部主机,也不会连接到另一个容器。在这种情况下,请在您的应用程序中使用服务名称 ,graph-db而不是localhost来连接到数据库。