Hello! Welcome to the next lesson in our journey to build a production-grade blog platform.
In our last session, we successfully assembled our entire application stack using Docker Compose. We have PostgreSQL, Kafka, and our three Spring Boot microservices—api-gateway, auth-service, and blog-service—all running as containers. We also took a crucial first step in container networking by configuring our services to connect to the database and Kafka using their service names (postgres and broker).
Today, we'll build on that foundation to enable true service-to-service communication. Our api-gateway is currently just listening on port 8080, but it doesn't know how to forward requests to the auth-service or blog-service. Our goal is to configure the routing logic that allows the gateway to act as the single entry point to our system, intelligently directing traffic to the correct downstream microservice based on the request path.
MERN Stack Comparison
In the MERN world, you might handle this with a reverse proxy like Nginx or by building a dedicated gateway service in Node.js/Express. In that gateway, you'd write logic to inspect the incoming request's URL (e.g., /api/auth/login) and then use a library like http-proxy-middleware to forward it to the appropriate internal service address (e.g., http://auth-service:8081).
The concept is identical here. We will configure Spring Cloud Gateway declaratively to do the same thing, but instead of writing imperative proxying code, we'll define routing rules in a properties file. The core mechanism—using service names for discovery within a Docker network—remains the same.
1. How Services Talk to Each Other in Docker Compose
Before we write any code, it's essential to solidify our understanding of how Docker networking enables this communication. When you run docker-compose up, Docker Compose automatically creates a private virtual network and attaches all the services defined in your docker-compose.yml file to it.
The most powerful feature of this private network is its built-in DNS resolver. This allows any container on the network to find and communicate with any other container on the same network simply by using its service name as a hostname.
To get a clear picture of this, let's review two excellent resources.
Docker Compose Networking Mysteries Service Discovery Failures ...
The article 'Docker Compose Networking Mysteries' explains the foundational concepts of Docker's internal networking and DNS. It clarifies why service names work as hostnames.
Please read the section titled 'How Compose Magically Builds Your Private Network'. Focus on understanding how the default network is created and the role of the internal DNS in resolving service names.
What is Docker Compose? Multiple Containers & Docker Networking
This video, 'What is Docker Compose?', provides a fantastic visual explanation of the same networking concept. Seeing it animated can help solidify the idea.
Watch from 08:58 to 11:02. This segment demonstrates exactly how Docker Compose creates an internal network and how a backend service container connects to a database container using its service name, not localhost.
This internal network and DNS are what allow our auth-service to connect to jdbc:postgresql://postgres:5432/blog_db. The hostname postgres is resolved by Docker's DNS to the internal IP address of the postgres container.

2. Configuring Routes in Spring Cloud Gateway
Now, let's apply this knowledge to our api-gateway. Spring Cloud Gateway works by defining a set of routes. Each route has:
- An ID: A unique name for the route.
- A URI: The destination where the request should be forwarded. This is where we'll use our service names!
- Predicates: Conditions that must be met for the route to be matched. The most common is
Path, which matches the request URL. - Filters: Optional components that can modify the request or response.
We will configure our gateway to route traffic as follows:
- Requests matching
/api/auth/**or/api/users/**go to theauth-service. - Requests matching
/api/posts/**go to theblog-service.
The URI will be specified using the lb:// scheme, like lb://auth-service. The lb stands for "load balancer". Spring Cloud Gateway integrates with a client-side load balancer which, in our Docker Compose setup, will use the service name to discover the correct container.
Let's see a practical example of this configuration pattern.
Spring Boot Microservices Project Example - Part 9 | Dockerize the application
The video 'Spring Boot Microservices Project Example' demonstrates exactly how to configure Spring Boot applications to communicate inside Docker. The presenter updates various service URLs from localhost to use container names, which is what we are about to do for our gateway.
Watch from 28:29 to 31:33. Pay close attention to how the application-docker.properties file is modified to point to services like zipkin, discovery-server, and keyclock using their container names. This directly mirrors the task you are about to perform.
3. Your Task: Implement Gateway Routing (20 minutes)
It's time to put this into practice. You'll update the gateway's configuration, rebuild its Docker image, and restart the stack.
-
Update Gateway Configuration:
Open theapplication-docker.propertiesfile for theapi-gatewayservice (located atmicroservices-new/api-gateway/src/main/resources/application-docker.properties).Add the following routing configuration:
# Define the port for the gateway itself server.port=8080 # Spring Cloud Gateway Routes spring.cloud.gateway.routes[0].id=auth-service-route spring.cloud.gateway.routes[0].uri=lb://auth-service spring.cloud.gateway.routes[0].predicates[0]=Path=/api/auth/**, /api/users/** spring.cloud.gateway.routes[1].id=blog-service-route spring.cloud.gateway.routes[1].uri=lb://blog-service spring.cloud.gateway.routes[1].predicates[0]=Path=/api/posts/**- Explanation: We've defined two routes. The first,
auth-service-route, matches any path starting with/api/auth/or/api/users/and forwards it to the service namedauth-service. The second route does the same for/api/posts/**andblog-service.
- Explanation: We've defined two routes. The first,
-
Rebuild the Gateway Image:
Because you've changed a file inside theapi-gatewayproject, you must rebuild its Docker image to include the new configuration.Navigate to your project's root directory (
microservices-new) in your terminal and run:# Navigate into the api-gateway directory cd api-gateway # Build the image docker build -t api-gateway:0.0.1 . # Return to the project root cd .. -
Relaunch the Stack:
Now, from the project root (microservices-new), bring your Docker Compose stack down and then back up. Using the--buildflag is a good practice to ensure any changed images are recreated, though we've already done it manually.docker-compose down docker-compose up -d
4. Runtime Observation & Debugging (15 minutes)
With the stack running, let's verify that our routing works.
-
Check Container Status:
First, ensure all services are running correctly.docker-compose psYou should see all containers in the
Upstate. -
Test the Route:
Let's try to register a user. This request will go tohttp://localhost:8080/api/auth/register, which should be routed by theapi-gatewayto theauth-service.Use
curlor Postman to send aPOSTrequest:curl -X POST http://localhost:8080/api/auth/register \ -H "Content-Type: application/json" \ -d '{ "username": "docker_user", "email": "docker@example.com", "password": "password123" }'If successful, you should get a response from the
auth-service, likely with the details of the newly created user. -
Inspect the Logs:
This is the core of "runtime-first" debugging. Let's trace the request.-
Gateway Log: Check the gateway's log to see it handling and forwarding the request.
docker-compose logs -f api-gatewayYou should see log lines indicating that a request to
/api/auth/registerwas received and routed tolb://auth-service. -
Auth Service Log: Now, check the
auth-servicelog.docker-compose logs -f auth-serviceYou should see the corresponding log lines showing that it received the request from the gateway, processed it, and likely interacted with the PostgreSQL database.
-
The localhost Confusion
A very common mistake is to configure the gateway to use localhost. For example, setting uri: http://localhost:8081. Let's clarify why this fails.
Docker Compose Networking Mysteries Service Discovery Failures ...
The 'Docker Compose Networking Mysteries' article has a specific section that addresses this exact pitfall.
Please read the subsection titled 'The localhost Confusion' under 'Mystery #2'. It perfectly explains why each container has its own localhost and why inter-container communication must use service names.
In short: localhost inside the api-gateway container refers to the api-gateway container itself, not your host machine or the auth-service container.
Conclusion
Excellent work! You have successfully configured service-to-service communication, a cornerstone of microservices architecture. The api-gateway now acts as a proper entry point, decoupling your clients from the internal network structure of your backend services.
Key Takeaways:
- Docker Compose creates a private network where services can resolve each other using their defined service names.
- Spring Cloud Gateway uses routes to forward requests, and the
uriof a route should use the service name (e.g.,lb://auth-service). - Communicating via
localhost:<port>between containers will fail, aslocalhostis scoped to each individual container. - Tracing a request by observing the logs of multiple services (
docker-compose logs -f <service-name>) is a fundamental debugging skill for distributed systems.
Preview of the Next Lesson:
Our configuration is working, but it's hardcoded in the application-docker.properties file inside our Docker image. If we wanted to change a database password or a route, we'd have to rebuild the image. This isn't flexible or secure. In the next lesson, we will externalize our configuration using environment variables in docker-compose.yml, allowing us to manage settings without touching the application code or images.