Using docker-compose, trying to connect a service in a container to mongoDb in another container

I am trying to connect a service in one docker container to a mongoDB in another container.
Researched on the net, and although it is asked a lot, no one seems to know the correct answer.

I have in my transaction-service

spring:
  application:
    name: transaction-service
server:
  port: '8083'

mongodb:
  connection:
    string: mongodb://172.21.0.2:27017
  database: transactions

172.21.0.2 is the container ip.

in my docker-compose.yml I have

version: "3"
services:
  mongo:
    image: mongo:latest
    container_name: "mongo"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: rootpassword
    ports:
      - 27017:27017
    networks:
      - banking-network
    volumes:
      - mongodb_data_container:/data/db

  transaction-service:
    image: transaction-service
    container_name: transaction-service
    build:
      context: transaction-service
      dockerfile: local.dockerfile
    ports:
      - "8083:8083"
    depends_on:
      - mongo
    environment:
      - MONGO_URL=mongodb://172.21.0.2:27017
    networks:
      - banking-network
networks:
  banking-network:
    external:
      name: banking-network

volumes:
  mongodb_data_container:

They are on the same network so mongodb://172.21.0.2:27017 should work, but I get a connection timeout.

I have also tried using the conatiner name mongo
ab1dd311ac4f mongo:latest “docker-entrypoint.s…” 50 seconds ago Up 47 seconds 0.0.0.0:27017->27017/tcp mongo

so used mongodb://mongo:27017 in both the application.yml and the docker-compose,yml

I thought all you needed was the ip of the docker container or the container name to connect.

Thanks for any help

Next time please paste your compose file in a Preformated text block (gear icon → </> icon) for better readability.

If you are trying to communicate with a container by its ip, you are high likely trying to do something that is not supposed to be used like that…

You declare a user defined network, which by default comes with dns-based service discovery. It is strongly recommended to use the target services name instead of its container ip for communication amongst containers in the same network as container ips are prone to change.

Since your MongDB service is named mongo, you can use MONGO_URL=mongodb://mongo:27017 to communicate from the transaction-service container to the mongo container.

Shouldn’t your environment variable be monodb.connection.string=mongodb://mongo:27017 instead of MONGO_URL=mongodb://mongo:27017? Or did you write an additional config class to implement an alternative way to set the variable for the connection?