sd1517
sd1517

Reputation: 647

Exception opening socket exception when trying to connect docker container to mongodb

I have a spring boot application which connects to a Mongo database. I have created a docker-compose file. The spring boot application has two instances. First instance runs on 8080 and 27017, which works perfectly fine. Now the second instance runs on 8083 and 27018. I can easily connect to 27017 and 27018 through Mongo GUI. However, when I run docker-compose up for the second instance, the spring boot gives the exception.

Following are my docker-compose files:

First Instance(docker-compose.yml):

version: '3'
services:
  app:
    container_name: HR-BACKEND
    restart: always
    build: .
    ports:
      - "8081:8080" #VF Webservice
    links:
      - mongo
 mongo:
    container_name: MONGOHR
    image: mongo:4.0.2
    ports:
      - "27017:27017"
    volumes:
      - /data/hrdb:/data/db

First Instance (application.properties)

spring.data.mongodb.uri=mongodb://mongo:27017/tsp

Second Instance(docker-compose.yml):

version: '3'
services:
  app:
    container_name: VF-BACKEND
    restart: always
    build: .
    ports:
      - "8083:8080" #VF Webservice
    links:
      - mongovf
 mongovf:
    container_name: MONGOVF
    image: mongo:4.0.2
    ports:
      - "27018:27017"
    volumes:
      - /data/hrdb:/data/db

Second Instance (application.properties)

spring.data.mongodb.uri=mongodb://mongovf:27018/tsp

Docker version:

Docker version 18.09.1, build 4c52b90

. I could not really find a solution in SO. Please let me know if more details are needed

Upvotes: 3

Views: 2249

Answers (1)

Thomasleveil
Thomasleveil

Reputation: 103965

In your second instance you are trying to connect to mongo on the wrong port. application.property should be:

spring.data.mongodb.uri=mongodb://mongovf:27017/tsp


In a docker compose context, you connect directly to containers without going through the docker host. This is why you have to connect directly to the container port instead of trying to connect through the port published on the docker host.

Upvotes: 4

Related Questions