Skip to content

Database using Docker

Maruf Bepary edited this page Mar 12, 2025 · 1 revision

Docker Setup for MongoDB with Spring Boot

Here's a complete setup guide for running MongoDB in Docker and connecting your Spring Boot application to it.

1. Docker Compose Setup

Create a docker-compose.yaml file in your project root:

version: '3.8'

services:
  mongodb:
    image: mongo:6.0
    container_name: mongodb
    ports:
      - "27017:27017"
    volumes:
      - mongodb_data:/data/db
    environment:
      - MONGO_INITDB_DATABASE=mydatabase
    command: mongod --noauth

volumes:
  mongodb_data:

2. Update Application Configuration

Update your src/main/resources/application.yaml to ensure it connects to the Docker MongoDB instance:

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: mydatabase
      
server:
  port: 8080

logging:
  level:
    org:
      springframework:
        data:
          mongodb:
            core:
              MongoTemplate: DEBUG

The configuration remains the same because Docker exposes MongoDB on the default port 27017 on localhost.

3. Step-by-Step MongoDB Docker Setup

Step 1: Start MongoDB using Docker Compose

Open a terminal in your project directory (where the docker-compose.yaml file is located) and run:

docker-compose up -d

This command starts MongoDB in detached mode (runs in the background).

Step 2: Verify MongoDB is Running

Check that the MongoDB container is running:

docker ps

You should see the MongoDB container in the list with status "Up".

Step 3: View MongoDB Logs (Optional)

If you want to see the MongoDB logs:

docker logs mongodb

Step 4: Access MongoDB Shell (Optional)

If you need to access the MongoDB shell for direct database operations:

docker exec -it mongodb mongosh

This opens the MongoDB shell where you can run commands like:

use mydatabase
db.products.find()

Step 5: Run Your Spring Boot Application

Now you can run your Spring Boot application, which will connect to the MongoDB instance running in Docker:

./gradlew bootRun

4. Testing the Setup

You can test your setup with the same curl commands provided earlier:

# Create a product
curl -X POST http://localhost:8080/api/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Test Product","description":"A test product","price":19.99}'

# Get all products
curl http://localhost:8080/api/products

5. Managing the MongoDB Container

Stopping MongoDB

When you're done working:

docker-compose down

This stops the MongoDB container but preserves the data volume.

Completely removing MongoDB and its data

If you want to completely remove the container and its data:

docker-compose down -v

The -v flag removes the volumes defined in the docker-compose file.

Restarting MongoDB

To restart the MongoDB container:

docker-compose restart