Java Notes
Containerizing and deploying Spring Boot microservices with Docker - Dockerfile, docker-compose, multi-service deployment, and production best practices.
Why Docker for Microservices?
In a microservices architecture, you might have 10, 20, or even 50 independent services, each with its own dependencies, runtime versions, and configuration. Without containerization, deploying and managing these services becomes a nightmare of conflicting library versions, port conflicts, and environment inconsistencies. A developer's machine might have Java 17, the test server has Java 11, and production has Java 21 — and suddenly your service behaves differently everywhere.
Docker solves this by packaging each microservice along with its exact runtime environment into a self-contained unit called a container. The container includes the JRE, application JAR, configuration, and all dependencies. It runs identically on a developer's laptop, a CI/CD server, and a production cluster.
| Without Docker | With Docker |
|---|---|
| "Works on my machine" problem | Consistent across all environments |
| Manual dependency installation | All dependencies packaged in container |
| Port conflicts between services | Isolated networking per container |
| Complex multi-service deployment | Single docker-compose up command |
| Hard to scale horizontally | Easy replication with orchestrators |
| Environment-specific configuration bugs | Identical behavior everywhere |
| Hours to set up new developer machines | Minutes with docker-compose up |
Docker Compose for Multi-Service Orchestration
Real microservices projects need multiple services running together. Docker Compose defines and manages all of them in a single YAML file:
Key design decisions explained:
depends_onwithcondition: service_healthyensures startup ordering — Eureka must be healthy before other services register- Environment variables override Spring Boot's
application.propertiesfor container-specific configuration - Named volumes (
pgdata) persist database data across container restarts and recreations - Service names act as DNS hostnames —
user-servicecan connect topostgres-db:5432by name deploy.replicas: 2runs two instances of user-service for load testing
Docker Networking
Docker Compose automatically creates a bridge network for all services in the file. Services communicate using their service names as DNS hostnames:
# Inside the Docker network:
# user-service reaches database at: postgres-db:5432
# api-gateway reaches user-service at: user-service:8081
# All services find Eureka at: eureka-server:8761
# Useful commands
docker network ls # List networks
docker network inspect myproject_default # See connected containers
docker-compose exec user-service ping postgres-db # Test connectivityFor production, you might create separate networks for frontend/backend isolation:
networks:
frontend: # Only API gateway exposed
backend: # Internal services onlyEssential Docker Commands
# Development workflow
docker-compose build # Build all images
docker-compose up -d # Start detached
docker-compose logs -f user-service # Follow logs
docker-compose ps # Check status
docker-compose down # Stop all
# Debugging
docker exec -it <container> /bin/sh # Shell into container
docker stats # Real-time resource usage
docker inspect <container> # Full container details
# Image management
docker images # List local images
docker image prune # Remove unused images
docker tag myapp:latest registry.io/myapp:v1.2 # Tag for registry
docker push registry.io/myapp:v1.2 # Push to registryProduction Best Practices
| Practice | Rationale |
|---|---|
Use specific image tags (temurin:17.0.9-jre) | Reproducible builds — latest is unpredictable |
| Multi-stage builds | Smaller images, faster pulls, reduced attack surface |
| Non-root container user | Limits damage if container is compromised |
| Health checks on every service | Orchestrators auto-restart unhealthy containers |
Resource limits (mem_limit, cpus) | Prevent runaway services from killing the host |
| Centralized logging (ELK/Loki) | Correlate logs across all containers |
| Image vulnerability scanning (Trivy) | Catch CVEs in base images before deployment |
.dockerignore file | Exclude .git, target/, IDE files from build context |
| Externalized configuration | Use env vars or config maps — never hardcode secrets |
| Container registry with access control | Docker Hub, AWS ECR, or Harbor for team image management |
| JVM container awareness flags | -XX:+UseContainerSupport respects container memory limits |
From Docker Compose to Kubernetes
Docker Compose is excellent for development and small deployments. For production at enterprise scale, Kubernetes adds:
- Auto-scaling: HPA (Horizontal Pod Autoscaler) adds/removes instances based on CPU, memory, or custom metrics
- Self-healing: Automatically restarts crashed containers and reschedules them on healthy nodes
- Rolling updates: Zero-downtime deployments with configurable rollout strategies
- Service mesh (Istio/Linkerd): Advanced traffic management, mTLS, observability between services
- Secret management: Encrypted storage for database passwords, API keys, TLS certificates
The same Docker images work in both Docker Compose and Kubernetes — only the orchestration layer changes.
Summary
Docker containerization is the foundation of modern microservices deployment. Multi-stage Dockerfiles create optimized, secure images. Docker Compose orchestrates multi-service environments for development and testing. Proper networking, health checks, and volume management ensure reliable operation. Following production best practices — non-root execution, resource limits, vulnerability scanning, and centralized logging — prepares your containerized Spring Boot microservices for enterprise-grade deployment, whether on Docker Compose for smaller systems or Kubernetes for large-scale production.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Docker Deployment.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, spring, framework, microservices
Related Java Master Course Topics