Issue Summary: I’m encountering a connection error between my Spring Boot application and a MongoDB database running in separate Docker containers.
Error Description: I’m receiving the following error:
com.mongodb.MongoSocketOpenException: Exception opening socket java.net.ConnectException: Connection refused
This indicates that my Spring Boot application is unable to connect to the MongoDB server.
Root Cause: The MongoDB server might not be running or isn’t accessible at the specified host and port (mongodb_instance:27017
).
application.properties
# Local MongoDB configuration
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase
application.yml (I think in this file I have a mistake)
spring:
profiles:
active: docker
data:
mongodb:
host: mongodb_instance
port: 27017
database: mydatabase
docker-compose.yml
version: '3.8'
services:
mongodb:
image: mongo:latest
container_name: mongodb_instance
ports:
- "27017:27017"
networks:
- backend
spring-app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
networks:
- backend
depends_on:
- mongodb
networks:
backend:
driver: bridge
dockerfile
# Use an appropriate base image for your Java application
FROM openjdk:17-jdk-slim AS build
# Set the working directory inside the container
WORKDIR /app
# Copy the Maven wrapper script and pom.xml to the container
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
# Copy the source code into the container
COPY src src
# Make the Maven wrapper executable
RUN chmod +x mvnw
# Build your application with Maven
RUN ./mvnw clean package -DskipTests
# Stage 2: Use a smaller base image for runtime
FROM openjdk:17-jdk-slim
# Set the working directory inside the container
WORKDIR /app
# Copy the built artifact from the build stage
COPY --from=build /app/target/simple-spring-mongodb-backup-0.0.1-SNAPSHOT.jar ./app.jar
# Expose the port your application runs on
EXPOSE 8080
# Specify the command to run your application
CMD ["java", "-Dspring.profiles.active=docker", "-jar", "./app.jar"]
I tried everything possible but no solution yet, I tried with
spring:
profiles:
active: docker
data:
mongodb:
host: 172.17.0.2 # Replace with the IP address of your MongoDB container
port: 27017
database: mydatabase # Replace with your actual database name
this config also but nothing works