Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two docker containers cannot communicate

I have two docker containers. One container is a database and the other is a web application. Web application calls the database through this link http://localhost:7200. However, the web application docker container cannot reach the database container.

I tried this docker-compose.yml, but does not work:

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"

So I have two containers: web application: http://localhost:8080/reasoner and this container calls a database in http://localhost:7200 which resides in a different container. However database container is not reachable by web container.

SOLUTION

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"

and replace http://localhost:7200 in web app code with http://graph-db:7200

like image 748
zoe vas Avatar asked Jan 24 '23 22:01

zoe vas


1 Answers

Do not use localhost to communicate between containers. Networking is one of the namespaces in docker, so localhost inside of a container only connects to that container, not to your external host, and not to another container. In this case, use the service name, graph-db, instead of localhost, in your app to connect to the db.

like image 57
BMitch Avatar answered Feb 15 '23 07:02

BMitch