In this article, let's see how we can dockerize a microservice-based application. We'll set up the configurations, build images, and write a Docker Compose file to run and manage the containers.
In this example, we'll use a Java Spring Boot application with 4 microservices.
- Discover-service for service discovery and loadbalancing
- Api-Gateway to route the requests and apply authenticaition
- Order-service
- Inventory-service
Step 1: Create new application-docker.yml file for docker profile under each service which will be selected during running of the containers. Put all the configurations as environment variable and those values will be passed from docker-compose file.
#Database Configuration for docker
spring:
datasource:
url: jdbc:postgresql://${DB_SERVER}:5432/${DB_NAME}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
Step 2: Now build images using maven plugin and then push the images to docker hub or directly use jib-maven-plugin to build and push the image.
Step 3: Now write compose file to pull and run the containers
version: "3.8"
services:
discovery-service:
image: smrutiranjanm/discovery-service
container_name: discovery-service
networks:
- ecommerce-network
ports:
- "8761:8761" # expose Eureka to host
api-gateway:
image: smrutiranjanm/api-gateway
container_name: api-gateway
networks:
- ecommerce-network
depends_on:
- order-service
- inventory-service
ports:
- "8080:8080"
order-db:
image: postgres:16-alpine
container_name: order-db
environment:
- POSTGRES_DB=orderDB
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=Root@123
networks:
- ecommerce-network
volumes:
- order-db-data:/var/lib/postgresql/data
order-service:
image: smrutiranjanm/order-service
container_name: order-service
environment:
SPRING_PROFILES_ACTIVE: docker
DB_SERVER: order-db
DB_NAME: orderDB
DB_USERNAME: postgres
DB_PASSWORD: Root@123
networks:
- ecommerce-network
depends_on:
- order-db
inventory-db:
image: postgres:16-alpine
container_name: inventory-db
environment:
- POSTGRES_DB=inventoryDB
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=Root@123
networks:
- ecommerce-network
volumes:
- inventory-db-data:/var/lib/postgresql/data
inventory-service:
image: smrutiranjanm/inventory-service
container_name: inventory-service
environment:
SPRING_PROFILES_ACTIVE: docker
DB_SERVER: inventory-db
DB_NAME: inventoryDB
DB_USERNAME: postgres
DB_PASSWORD: Root@123
networks:
- ecommerce-network
depends_on:
- inventory-db
volumes:
order-db-data:
inventory-db-data:
networks:
ecommerce-network:
That's it, now when we will run this docker compose file it will pull and start the containers.
Dockerizing a microservice-based application simplifies deployment and environment management. By containerizing each service, managing configurations through environment variables, and orchestrating them with Docker Compose, we can run the entire system reliably with a single command. This approach improves portability, scalability, and makes local development and production environments consistent.