-
Notifications
You must be signed in to change notification settings - Fork 0
Database using Docker
Here's a complete setup guide for running MongoDB in Docker and connecting your Spring Boot application to it.
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:
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.
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).
Check that the MongoDB container is running:
docker ps
You should see the MongoDB container in the list with status "Up".
If you want to see the MongoDB logs:
docker logs mongodb
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()
Now you can run your Spring Boot application, which will connect to the MongoDB instance running in Docker:
./gradlew bootRun
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
When you're done working:
docker-compose down
This stops the MongoDB container but preserves the data volume.
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.
To restart the MongoDB container:
docker-compose restart