Ports and Configuration

One Port per Service

On your laptop every service runs on localhost, so each needs a different port. In Docker or Kubernetes each service gets its own host name, and they can all use 8080 inside their containers.

ServiceLocal portDatabaseInside Docker Compose
api-gateway (later)8080-http://api-gateway:8080
product-service8081product_dbhttp://product-service:8081
order-service8082order_dbhttp://order-service:8082
user-service8083user_dbhttp://user-service:8083
payment-service8084payment_dbhttp://payment-service:8084

order-service application.yml

server:
  port: 8082

spring:
  application:
    name: order-service
  datasource:
    url: jdbc:h2:mem:order_db
  jpa:
    hibernate:
      ddl-auto: update

shopease:
  services:
    product-url: ${PRODUCT_SERVICE_URL:http://localhost:8081}
    timeout:
      connect: 2s
      read: 3s

Tip: ${PRODUCT_SERVICE_URL:http://localhost:8081} means "use the environment variable if it is set, else the default". Later, service discovery replaces fixed URLs with a name like http://product-service.

Typed Configuration with @ConfigurationProperties

package com.shopease.order.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;

@ConfigurationProperties(prefix = "shopease.services")
public record ServiceUrls(String productUrl, Timeout timeout) {
    public record Timeout(Duration connect, Duration read) {}
}

// enable it once, e.g. on the main class:
@SpringBootApplication
@ConfigurationPropertiesScan
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}

Note: Relaxed binding maps product-url in YAML to the productUrl record component, and 2s to a Duration of 2 seconds.

Practice

Exercise: You start order-service on your laptop and see Web server failed to start. Port 8082 was already in use. Give two ways to fix it.

Show answer
1. Stop the other process using 8082
   (Windows: netstat -ano | findstr :8082  then  taskkill /PID <pid> /F;
    Linux/macOS: lsof -i :8082  then  kill <pid>).
2. Run on another port without editing files:
   SERVER_PORT=8092 ./mvnw spring-boot:run
   or  java -jar order-service.jar --server.port=8092
(If you change it, also update whoever calls order-service.)