I'm trying to connect my Spring Boot application (using spring-boot-starter-data-mongodb) to a MongoDB instance within a shared Docker network managed by docker-compose.
The connection is failing, and my application appears to be attempting to connect to the default MongoDB address (mongodb://localhost:27017) instead of the host/port I've configured for the Docker network. This suggests my configuration is being ignored or overridden due to Spring Boot's Externalized Configuration precedence.
My Setup
1. docker-compose.yml
YAML
services:
# 1. MongoDB Service
mongodb:
image: mongo:latest
container_name: mongodb
ports:
# Exposing for external access/testing, but internal communication doesn't use this port mapping
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: myuser
MONGO_INITDB_ROOT_PASSWORD: mypassword
volumes:
- mongo_data:/data/db
# 2. Spring Boot Application Service
myapp:
build: .
container_name: myapp
ports:
- "8080:8080"
depends_on:
- mongodb
# --- CRITICAL AREA ---
environment:
# These properties seem to be failing to correctly configure the connection:
SPRING_DATA_MONGODB_HOST: mongodb
SPRING_DATA_MONGODB_PORT: 27017
SPRING_DATA_MONGODB_USERNAME: myuser
SPRING_DATA_MONGODB_PASSWORD: mypassword
SPRING_DATA_MONGODB_DATABASE: mydatabase
volumes:
mongo_data:
2. Spring Boot application.yaml (or application-prod.yaml)
This is the internal configuration I'm trying to override:
YAML
spring:
data:
mongodb:
host: localhost # This is the value I expect to be overridden
port: 27017
database: mydatabase
username: myuser
password: mypassword
The Problem
My application logs show a connection attempt to
mongodb://localhost:27017or a connection timeout error.I suspect the environment variables in my
docker-compose.ymlare either incorrectly formatted for Spring Boot's relaxed binding or not taking effect, allowing the default settings (or the values inapplication.yaml) to take precedence.
What is the correct and most robust way to configure Spring Boot's MongoDB connection string using the Docker Compose service name, ensuring it correctly overrides any configuration inside my JAR?
I am specifically looking for confirmation on:
The correct environment variable format for the full connection URI (e.g.,
SPRING_DATA_MONGODB_URI).Why using
SPRING_DATA_MONGODB_HOST: mongodbis failing to override thelocalhostsetting.
spring.mongodbinsteda ofspring.data.mongodbnamespace. So you are baiscally using the wrong properties. See the migration guides.