E.Bülbül
E.Bülbül

Reputation: 39

Getting "Exception opening socket" on Mongodb connection from Spring App (docker-compose)

Even though I'm giving in the application properties,

spring.data.mongodb.host=api-database4

as the hostname which is the container name and hostname of the MongoDB on the docker-compose file, Spring app still can't connect to the MongoDB instance. I can however connect from MongoDB Compass to localhost:27030 but not to mongodb://api-database4:27030/messagingServiceDb.

My docker-compose file;

version: '3'

services:
  messaging-api6:
    container_name: 'messaging-api6'
    build: ./messaging-api
    restart: always
    ports:
      - 8085:8080
    depends_on:
      - api-database4
    networks:
      - shared-net

  api-database4:
    image: mongo
    container_name: api-database4
    hostname: api-database4
    restart: always
    ports:
      - 27030:27017
    networks:
      - shared-net
    command: mongod --bind_ip_all

networks:
  shared-net:
    driver: bridge

and my Docker file for the Spring app is;

FROM openjdk:12-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

and my application.properties are;

#Local MongoDB config
spring.data.mongodb.database=messagingServiceDb
spring.data.mongodb.port=27030
spring.data.mongodb.host=api-database4

Entire code can be seen here.

How can I make my spring app on a docker container create a connection to the MongoDB instance which is on another docker container?

I have tried the solutions on similar questions and replicated them, it still gives the same error.

Spring app's logs

Edit and Solution:

I solved the issue by commenting out configuration below,

#Local MongoDB config
#spring.data.mongodb.database=messagingServiceDb
spring.data.mongodb.host=api-database4
spring.data.mongodb.port=27030

The remaining question is, why? That was the correct port that I'm trying to connect. Could it be related to the configuration order?

Upvotes: 0

Views: 523

Answers (1)

Maciej Kozik
Maciej Kozik

Reputation: 176

ports directive in docker-compose publishes container ports to the host machine. The containers communicate with each other on exposed ports. You can test whether a container can reach another with netcat.

docker exec -it messaging-api6 bash
> apt-get install netcat
> nc -z -v api-database4 27030
> nc -z -v api-database4 27017

Upvotes: 1

Related Questions