Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Orchestrating Local Services with Docker Compose

This lesson is built with resources from youtube.com, github.com and 1 more site.

Welcome back! In the last lesson, we successfully created optimized, multi-stage Docker images for all our microservices: api-gateway, auth-service, and blog-service. We now have the fundamental building blocks, but they exist in isolation.

This lesson is where we bring it all together. Our goal is to use Docker Compose to define and run our entire application stack—the database, the message broker, and all our custom services—with a single command. This will create a fully functional, containerized local development environment, a critical milestone for any microservices project.

MERN Stack Comparison

You're likely familiar with using docker-compose.yml to spin up a Node.js backend, a database like MongoDB, and perhaps a Redis cache. The core principles you know still apply directly: defining services, mapping ports, and managing data with volumes.

The main evolution here is the complexity of our stack. We will be orchestrating multiple backend services that need to discover and communicate with each other, a relational database (PostgreSQL), and a distributed messaging system (Kafka). We'll pay special attention to how we pass configuration to our Spring Boot services from Docker Compose, a crucial pattern for managing containerized applications.



1. Understanding the docker-compose.yml File

At its heart, a docker-compose.yml file is a declarative recipe for a multi-container application. It tells Docker's compose tool which containers to run and how to configure them to work together.

Here are the key fields we'll use today:

  • version: Specifies the file format version.
  • services: The main section where each container is defined as a service.
  • image: The Docker image to use for the service (e.g., postgres:15 or our own blog-service:0.0.1).
  • container_name: A static, human-readable name for the container.
  • ports: Maps ports from the host machine to the container (e.g., "8080:8080").
  • environment: Sets environment variables inside the container. This is how we'll configure our Spring Boot applications.
  • volumes: Persists data outside the container's lifecycle, essential for our database.
  • depends_on: Controls the startup order of services.

Let's build our file piece by piece, starting with the infrastructure.


2. Defining Infrastructure Services

A robust system is built on a solid foundation. In our case, this means setting up our database and message broker first.

Create a new file named docker-compose.yml in the root of your project (microservices-new/docker-compose.yml).

PostgreSQL Database

First, let's define the PostgreSQL service. Add the following to your docker-compose.yml:

version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=blog_db
    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:

Let's break this down:

  • image: postgres:15-alpine: We use the official PostgreSQL image, opting for the lightweight alpine variant.
  • ports: - "5432:5432": We map the standard Postgres port on our host machine to the container, so we can connect to it with a database client if needed.
  • environment: These variables are used by the Postgres image on its first run to initialize the database, create a user, and set a password.
  • volumes: This is critical. postgres-data:/var/lib/postgresql/data tells Docker to mount a named volume called postgres-data to the directory where Postgres stores its data files inside the container. This ensures that even if we destroy and recreate the postgres container, our data remains intact. We declare the named volume at the bottom of the file.

Kafka and Zookeeper

Next, we'll set up Kafka. Kafka relies on Zookeeper for metadata management (in the version we're using), so we need to define both. This setup can be complex, so watching a focused explanation is helpful.

Easy Way to Setup and Connect Kafka to SpringBoot - Microservices

The video 'Easy Way to Setup and Connect Kafka to SpringBoot' provides a crystal-clear, line-by-line explanation of a Docker Compose setup for Kafka. We will use the same configuration.

Watch from 10:43 to 22:03. The presenter meticulously builds the Zookeeper and Kafka service definitions. Pay close attention to how environment variables like KAFKA_ZOOKEEPER_CONNECT and KAFKA_ADVERTISED_LISTENERS are configured to enable communication.

Based on the video, add the zookeeper and broker (Kafka) services to your docker-compose.yml file under the services section:




# ... (postgres service above)

  zookeeper:
    image: confluentinc/cp-zookeeper:7.0.1
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-kafka:7.0.1
    container_name: broker
    ports:
      - "9092:9092"
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://broker:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0

Key points here:

  • depends_on: - zookeeper: This tells Docker Compose to start the zookeeper service and wait for it to be healthy before starting the broker service.
  • KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181': The Kafka broker connects to Zookeeper using its service name, zookeeper, as the hostname. This is Docker's internal DNS at work!
  • KAFKA_ADVERTISED_LISTENERS: This is the trickiest part. It defines how clients can connect to Kafka.
    • PLAINTEXT://localhost:9092: For clients outside the Docker network (like our IDE or Postman on the host machine).
    • PLAINTEXT_INTERNAL://broker:29092: For clients inside the Docker network (like our other Spring Boot services). They will connect using the hostname broker on port 29092.

3. Defining Our Application Services

With the infrastructure in place, we can now add our own Spring Boot microservices.

Microservices Architecture with Kafka and Spring Boot
This diagram shows a similar architecture to what we're building. A request flows through an API layer, which can interact with other services via Kafka and a persistence layer connected to a PostgreSQL database. Our `docker-compose.yml` is the code that makes this diagram a running reality.

Add the definitions for auth-service, blog-service, and api-gateway to your services block:




# ... (broker service above)

  auth-service:
    image: auth-service:0.0.1
    container_name: auth-service
    ports:
      - "8081:8081"
    depends_on:
      - postgres
      - broker
    environment:
      - SPRING_PROFILES_ACTIVE=docker

  blog-service:
    image: blog-service:0.0.1
    container_name: blog-service
    ports:
      - "8082:8082"
    depends_on:
      - postgres
      - broker
    environment:
      - SPRING_PROFILES_ACTIVE=docker

  api-gateway:
    image: api-gateway:0.0.1
    container_name: api-gateway
    ports:
      - "8080:8080"
    depends_on:
      - auth-service
      - blog-service
    environment:
      - SPRING_PROFILES_ACTIVE=docker

Here, we're doing three things:

  1. Using the images we built in the last lesson.
  2. Mapping the correct ports (8081, 8082, 8080).
  3. Setting SPRING_PROFILES_ACTIVE=docker. This is a powerful Spring Boot feature. It tells our applications to load configuration from a file named application-docker.properties instead of the default application.properties. This allows us to have separate configurations for local running vs. Docker running.

4. Configuring Services for the Docker Network

Our services are defined, but they still think the database and Kafka are on localhost. We need to create application-docker.properties for each service to point them to the correct hostnames within the Docker network.

Your Task: Create Docker-Specific Configurations (15 minutes)

  1. For auth-service and blog-service:

    • In src/main/resources for both services, create a new file: application-docker.properties.
    • Add the following content. This overrides the default properties to use the service names (postgres, broker) as hostnames.
    
    
    
    # /auth-service/src/main/resources/application-docker.properties
    # /blog-service/src/main/resources/application-docker.properties
    
    
    
    
    # Point to the 'postgres' container
    spring.datasource.url=jdbc:postgresql://postgres:5432/blog_db
    spring.datasource.username=admin
    spring.datasource.password=password
    
    
    
    
    # Point to the 'broker' container
    spring.kafka.bootstrap-servers=broker:29092
    
    
    
    
    # Ensure schema is created/updated by Hibernate
    spring.jpa.hibernate.ddl-auto=update
    
  2. For api-gateway: We don't have database or Kafka settings here, so you just need to create an empty application-docker.properties file in its src/main/resources directory for now.

  3. Rebuild your images: Since you've added new files, you need to rebuild your Docker images. From the project root (microservices-new), run the build command for each service:

    
    
    
    # Make sure you are in the root directory of each service
    cd auth-service && docker build -t auth-service:0.0.1 . && cd ..
    cd blog-service && docker build -t blog-service:0.0.1 . && cd ..
    cd api-gateway && docker build -t api-gateway:0.0.1 . && cd ..
    

5. Launching and Debugging the Stack

Your complete docker-compose.yml should now look like the combination of all the snippets above. Now for the moment of truth.

Your Task: Launch the Application (10 minutes)

  1. Launch Docker Compose: From the root of your project (where your docker-compose.yml is located), run the following command:

    docker-compose up -d
    

    The -d flag runs the containers in "detached" mode, meaning they run in the background.

  2. Runtime Observation & Debugging:

    • First, check if all containers started successfully:

      docker-compose ps
      

      You should see all five services (postgres, zookeeper, broker, auth-service, blog-service, api-gateway) with a State of Up.

    • If a service is not Up or is constantly restarting, it's time to check the logs. This is the core of the "debugging-first" mindset. For example, to check the logs of the auth-service:

      docker-compose logs -f auth-service
      

      The -f flag "follows" the log output in real-time. Look for stack traces. A common error would be a java.net.ConnectException: Connection refused if it cannot reach the postgres or broker container. This usually points to a misconfiguration in application-docker.properties or the docker-compose.yml file.

    • Tail the logs for each of your services to see them start up. You should see the familiar Spring Boot banner followed by log lines indicating they've connected to the database and Kafka.



Conclusion

Congratulations! You have successfully orchestrated a multi-service, event-driven application using Docker Compose. You've defined infrastructure, configured your custom services to communicate within a Docker network, and learned how to debug the stack by inspecting container logs. This is a foundational skill for any backend or platform engineer.

Key Takeaways:

  • docker-compose.yml provides a single source of truth for defining and running your entire local development stack.
  • Services within a Docker Compose network can communicate with each other using their service names as hostnames.
  • Spring Profiles (application-docker.properties) are a clean way to manage environment-specific configurations.
  • docker-compose logs is your most important tool for debugging startup and runtime issues in a containerized environment.

Preview of the Next Lesson:
Our services are running, but their configurations (like database passwords) are hardcoded. In the next lesson, we will address this by learning how to externalize configuration from our Docker images using environment variables in docker-compose.yml, making our setup more secure and flexible.