πΈοΈ Service Mesh Virtualization, Subnet Segmentation & Distributed Topology
While running a single test container against a monolithic API mock is sufficient for basic functional tests, enterprise microservice architectures demand end-to-end testing across distributed service meshes. Real-world API gateways orchestrate transactions across multiple distinct dependencies: an OAuth2 Authorization Server, a primary Relational Database (PostgreSQL/MySQL), a distributed Redis Cache, an asynchronous message broker (RabbitMQ/Kafka), and downstream third-party partner APIs (e.g., payment gateways and SMS notifications). Docker Compose Test Mesh Architecture provides an isolated, multi-tiered container infrastructure running on private, dual-homed bridge networks. By partitioning services across public frontend subnets and isolated data subnets, configuring specialized mock instances, evaluating multi-stage container health cascades (condition: service_healthy), and injecting end-to-end W3C Trace Context correlation headers in REST Assured, test architects simulate realistic production topologies on local workstations and CI agents with zero external dependencies.
DUAL-HOMED DOCKER COMPOSE TEST MESH ARCHITECTURE:
[PUBLIC SUBNET: "frontend-tier" (172.30.1.0/24)] [PRIVATE SUBNET: "backend-data-tier" (172.30.2.0/24)]
ββββββββββββββββββββββββββββββββββββββββββββββββ
β CONTAINER: rest-assured-runner (172.30.1.10) β
β β’ Dispatches API Tests via REST Assured β
β β’ Connected strictly to "frontend-tier" β
β β’ Volume mounts ./target/allure-results β
ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (HTTP / JSON Wire Call)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CONTAINER: api-gateway (DUAL-HOMED BRIDGE CONTAINER) β
β β’ Frontend IP: 172.30.1.20 | Backend IP: 172.30.2.20 β
β β’ Reverse proxy, JWT authentication check, rate limiting, and route routing β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββ
βΌ (Direct SQL Queries) βΌ (Cache Queries) βΌ (HTTP Mock Call)
ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ
β CONTAINER: postgres-db β β CONTAINER: redis-cache β β CONTAINER: mock-wiremock β
β IP: 172.30.2.30 β β IP: 172.30.2.40 β β IP: 172.30.2.50 β
β Port: 5432 (Internal Only) β β Port: 6379 (Internal Only) β β Port: 8080 (Internal Only) β
β RDBMS Table Persistence β β Distributed Token & State β β Simulates Partner Gateways β
ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ
β²
β (Security Isolation Guard)
β΄
REST-ASSURED-RUNNER CANNOT REACH POSTGRES OR REDIS DIRECTLY OVER FRONTEND-TIER!
ENFORCES AUTHENTICATION & NETWORK BOUNDARY INTEGRITY DURING REGRESSION TESTING!
version: '3.8'
networks:
frontend-mesh:
driver: bridge
ipam:
config:
- subnet: 172.30.1.0/24
backend-data-mesh:
driver: bridge
internal: true # Disallows external outbound internet routing for security isolation
ipam:
config:
- subnet: 172.30.2.0/24
services:
# ============================================================================
# 1. DOWNSTREAM MOCK SIMULATOR (WireMock: Auth & Payment Gateway)
# ============================================================================
mock-wiremock:
image: wiremock/wiremock:3.5.2-alpine
container_name: mesh-mock-wiremock
networks:
backend-data-mesh:
ipv4_address: 172.30.2.50
volumes:
- ./src/test/resources/mesh/mappings:/home/wiremock/mappings
- ./src/test/resources/mesh/__files:/home/wiremock/__files
command: ["--global-response-templating", "--verbose"]
healthcheck:
test: ["CMD", "nc", "-z", "localhost", "8080"]
interval: 3s
timeout: 2s
retries: 5
# ============================================================================
# 2. DISTRIBUTED CACHE & SESSION STORE (Redis 7)
# ============================================================================
redis-cache:
image: redis:7.2-alpine
container_name: mesh-redis-cache
networks:
backend-data-mesh:
ipv4_address: 172.30.2.40
command: ["redis-server", "--appendonly", "no", "--requirepass", "RedisMeshPass#2026"]
healthcheck:
test: ["CMD", "redis-cli", "-a", "RedisMeshPass#2026", "ping"]
interval: 3s
timeout: 2s
retries: 5
# ============================================================================
# 3. RELATIONAL PERSISTENCE (PostgreSQL 16)
# ============================================================================
postgres-db:
image: postgres:16-alpine
container_name: mesh-postgres-db
networks:
backend-data-mesh:
ipv4_address: 172.30.2.30
environment:
POSTGRES_DB: masterclass_db
POSTGRES_USER: sdet_admin
POSTGRES_PASSWORD: DbSecurePass#2026
volumes:
- ./src/test/resources/mesh/sql/init-postgres.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U sdet_admin -d masterclass_db"]
interval: 4s
timeout: 3s
retries: 8
# ============================================================================
# 4. SYSTEM UNDER TEST: API GATEWAY (Dual-Homed Microservice)
# ============================================================================
api-gateway:
image: nginx:alpine
container_name: mesh-api-gateway
networks:
frontend-mesh:
ipv4_address: 172.30.1.20
backend-data-mesh:
ipv4_address: 172.30.2.20
volumes:
- ./src/test/resources/mesh/nginx/gateway.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
mock-wiremock:
condition: service_healthy
redis-cache:
condition: service_healthy
postgres-db:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://localhost:8080/health"]
interval: 3s
timeout: 2s
retries: 5
# ============================================================================
# 5. REST ASSURED TEST RUNNER CONTAINER
# ============================================================================
rest-assured-mesh-runner:
build:
context: .
dockerfile: Dockerfile
target: test-runner
container_name: mesh-test-runner
networks:
frontend-mesh:
ipv4_address: 172.30.1.10
depends_on:
api-gateway:
condition: service_healthy
environment:
- env=mesh
- API_GATEWAY_URL=http://api-gateway:8080
- X_CORRELATION_ROOT=TRACE-MESH-RUNNER-01
volumes:
- ./target/allure-results:/app/target/allure-results
- ./target/failure-dumps:/app/target/failure-dumps
# ==============================================================================
# REVERSE PROXY & API GATEWAY CONFIGURATION FOR DOCKER TEST MESH
# Listens on port 8080 and routes to backend mock and microservice containers
# ==============================================================================
server {
listen 8080;
server_name api-gateway;
# Healthcheck probe for Docker Compose health evaluation
location /health {
access_log off;
default_type application/json;
return 200 '{"status":"UP","meshNodes":{"wiremock":"READY","redis":"READY","postgres":"READY"}}';
}
# Route 1: Student Management Endpoints -> Dispatches to Mock WireMock
location /v1/students {
proxy_pass http://mock-wiremock:8080/v1/students;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Gateway-Routed "true";
proxy_set_header X-Correlation-Id $http_x_correlation_id;
}
# Route 2: Payment Gateway Endpoints -> Dispatches to Mock WireMock Payment Service
location /v1/payments {
proxy_pass http://mock-wiremock:8080/v1/payments;
proxy_set_header Host $host;
proxy_set_header X-Gateway-Routed "true";
proxy_set_header X-Correlation-Id $http_x_correlation_id;
}
# Route 3: Auth Server Endpoints -> Dispatches to Mock WireMock Auth Server
location /oauth/v2 {
proxy_pass http://mock-wiremock:8080/oauth/v2;
proxy_set_header Host $host;
proxy_set_header X-Gateway-Routed "true";
}
}
-- ==============================================================================
-- POSTGRESQL INITIALIZATION SCRIPT FOR DOCKER TEST MESH
-- Executed on container startup by /docker-entrypoint-initdb.d/init.sql
-- ==============================================================================
\connect masterclass_db;
CREATE SCHEMA IF NOT EXISTS academic;
CREATE TABLE IF NOT EXISTS academic.students (
student_id VARCHAR(64) PRIMARY KEY,
full_name VARCHAR(150) NOT NULL,
email VARCHAR(150) UNIQUE NOT NULL,
academic_track VARCHAR(80) NOT NULL,
enrolled_credits INT NOT NULL DEFAULT 0,
status VARCHAR(30) NOT NULL DEFAULT 'ACTIVE',
tenant_region VARCHAR(50) NOT NULL DEFAULT 'MH-PUNE-WEST',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Seed pre-existing baseline student records for retrieval and update tests
INSERT INTO academic.students (student_id, full_name, email, academic_track, enrolled_credits, status, tenant_region)
VALUES
('STU-88219', 'Nikita Sharma', 'nikita.sharma@nikita-infotech.com', 'ENTERPRISE_AUTOMATION', 16, 'ACTIVE', 'MH-PUNE-WEST'),
('STU-88220', 'Aarav Deshmukh', 'aarav.deshmukh@nikita-infotech.com', 'FULLSTACK_SDET', 12, 'ACTIVE', 'MH-PUNE-WEST'),
('STU-77100', 'Rohan Verma', 'rohan.verma@nikita-infotech.com', 'CLOUD_DEVOPS_QA', 14, 'SUSPENDED', 'MH-PUNE-WEST')
ON CONFLICT (student_id) DO NOTHING;
traceparent) and X-Correlation-Id headers to trace requests as they traverse the gateway and mock services.
package com.nikita.restassured.mesh;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import java.util.UUID;
public class MeshCorrelationFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
long threadId = Thread.currentThread().getId();
// 1. Generate unique correlation token
String correlationId = "CORR-MESH-" + threadId + "-" + UUID.randomUUID().toString().substring(0, 8);
requestSpec.header("X-Correlation-Id", correlationId);
// 2. Synthesize W3C Traceparent Header (version-traceid-spanid-traceflags)
String traceId = UUID.randomUUID().toString().replace("-", "");
String spanId = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
String traceParent = String.format("00-%s-%s-01", traceId, spanId);
requestSpec.header("traceparent", traceParent);
long startEpoch = System.currentTimeMillis();
// 3. Transmit call over Docker mesh bridge
Response response = ctx.next(requestSpec, responseSpec);
long durationMs = System.currentTimeMillis() - startEpoch;
System.out.printf("[MESH TRACE] %s %s β HTTP %d (Duration: %d ms | Trace: %s)%n",
requestSpec.getMethod(), requestSpec.getURI(),
response.getStatusCode(), durationMs, correlationId);
return response;
}
}
package com.nikita.restassured.mesh;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
public class DockerMeshIntegrationTest {
private RequestSpecification gatewaySpec;
@BeforeClass
public void setupMeshSpecification() {
// Resolve gateway hostname: Defaults to http://api-gateway:8080 inside container, localhost:8080 on host
String gatewayUrl = System.getenv().getOrDefault("API_GATEWAY_URL", "http://api-gateway:8080");
gatewaySpec = new RequestSpecBuilder()
.setBaseUri(gatewayUrl)
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
// Attach mesh correlation filter for distributed tracing
.addFilter(new MeshCorrelationFilter())
.build();
System.out.println("[*] DockerMeshIntegrationTest initialized against gateway: " + gatewayUrl);
}
@Test(description = "Verify Gateway healthcheck returns UP with healthy mesh node dependencies")
public void testGatewayHealthcheckProbe() {
given()
.spec(gatewaySpec)
.when()
.get("/health")
.then()
.statusCode(200)
.body("status", equalTo("UP"))
.body("meshNodes.wiremock", equalTo("READY"))
.body("meshNodes.postgres", equalTo("READY"));
System.out.println("[β] Gateway health check verified: All mesh dependencies are UP.");
}
@Test(description = "Verify student query routes through API Gateway to WireMock backend")
public void testStudentRoutingThroughMeshGateway() {
given()
.spec(gatewaySpec)
.pathParam("studentId", "STU-88219")
.when()
.get("/v1/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"))
.body("data.fullName", equalTo("Nikita Sharma"))
// Verify reverse proxy injected routing marker header:
.header("X-Gateway-Routed", equalTo("true"));
System.out.println("[β] Student query successfully traversed the API Gateway mesh to WireMock.");
}
@Test(description = "Verify payment initiation endpoint routes correctly through gateway")
public void testPaymentRoutingThroughMeshGateway() {
String paymentPayload = "{\"studentId\": \"STU-88219\", \"amount\": 24000.00, \"currency\": \"INR\"}";
given()
.spec(gatewaySpec)
.body(paymentPayload)
.when()
.post("/v1/payments")
.then()
.statusCode(200)
.body("paymentStatus", equalTo("INITIATED"))
.body("transactionId", notNullValue())
.header("X-Gateway-Routed", equalTo("true"));
System.out.println("[β] Payment payload routed successfully across the container mesh.");
}
}
#!/usr/bin/env bash
# ==============================================================================
# SCRIPT: launch-mesh.sh
# Purpose: Orchestrates full Docker Compose Test Mesh build, execution & teardown
# ==============================================================================
set -e
COMPOSE_FILE="docker-compose.mesh.yml"
echo "=============================================================================="
echo " LAUNCHING ENTERPRISE DOCKER COMPOSE TEST MESH"
echo "=============================================================================="
# Pre-create output directories on host with open permissions for container writes
mkdir -p target/allure-results target/failure-dumps target/allure-report
chmod -R 777 target/
# Step 1: Clean up any orphaned containers or networks from previous runs
echo "[*] Cleaning up orphaned containers and networks..."
docker compose -f $COMPOSE_FILE down -v --remove-orphans
# Step 2: Build the test runner container image
echo "[*] Building REST Assured runner image..."
docker compose -f $COMPOSE_FILE build rest-assured-mesh-runner
# Step 3: Launch mesh dependencies (Database, Cache, Mock, Gateway)
echo "[*] Spinning up mesh dependencies..."
docker compose -f $COMPOSE_FILE up -d mock-wiremock redis-cache postgres-db api-gateway
# Step 4: Wait for API Gateway healthcheck probe to report healthy
echo "[*] Waiting for API Gateway and upstream services to become healthy..."
until [ "$(docker inspect --format='{{.State.Health.Status}}' mesh-api-gateway 2>/dev/null)" == "healthy" ]; do
printf "."
sleep 2
done
echo ""
echo "[+] API Gateway is HEALTHY. All upstream mesh nodes operational."
# Step 5: Execute test runner container and capture exit code
echo "[*] Executing REST Assured test suite inside mesh runner..."
set +e
docker compose -f $COMPOSE_FILE up --abort-on-container-exit --exit-code-from rest-assured-mesh-runner rest-assured-mesh-runner
RUNNER_EXIT_CODE=$?
set -e
# Step 6: Gracefully tear down all containers and networks
echo "[*] Tearing down test mesh infrastructure..."
docker compose -f $COMPOSE_FILE down -v
echo "=============================================================================="
echo " TEST MESH EXECUTION FINISHED WITH EXIT CODE: ${RUNNER_EXIT_CODE}"
echo "=============================================================================="
exit $RUNNER_EXIT_CODE
name: Multi-Service Docker Compose Test Mesh CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
run-test-mesh:
name: Execute Tests in Multi-Tier Docker Mesh
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- name: Checkout Codebase
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Prepare Host Directories for Artifact Mounting
run: |
mkdir -p target/allure-results target/failure-dumps
chmod -R 777 target/
- name: Launch Test Mesh & Run Tests
run: |
./src/test/resources/mesh/scripts/launch-mesh.sh
- name: Teardown Mesh Infrastructure (Always Executes)
if: always()
run: |
docker compose -f docker-compose.mesh.yml down -v --remove-orphans
- name: Upload Allure Results Artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: mesh-allure-results
path: target/allure-results/
retention-days: 7
- name: Upload Failure Diagnostics (If Tests Failed)
if: failure()
uses: actions/upload-artifact@v4
with:
name: mesh-failure-dumps
path: target/failure-dumps/*.log
retention-days: 14
UnknownHostException on segregated subnets, inspecting Docker bridge routes via docker network inspect, and verifying firewall boundary enforcement.
package com.nikita.restassured.mesh;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetworkSegregationTriageTest {
// ==========================================================================
// VERIFYING NETWORK SEGREGATION ENFORCEMENT
// The test runner container sits exclusively on "frontend-mesh" (172.30.1.0/24).
// The PostgreSQL database sits exclusively on "backend-data-mesh" (172.30.2.0/24).
//
// The test runner MUST NOT be able to resolve or connect directly to "postgres-db"!
// Direct access must fail, proving the network boundary is enforced.
// ==========================================================================
@Test(description = "Verify test runner container cannot resolve backend database hostname directly")
public void testBackendSubnetIsolationEnforced() {
String backendHost = "postgres-db";
try {
InetAddress address = InetAddress.getByName(backendHost);
Assert.fail("SECURITY VIOLATION: Test runner resolved isolated backend host: " + address.getHostAddress());
} catch (UnknownHostException expected) {
System.out.println("[β] Verified Network Isolation: 'postgres-db' hostname is unreachable from frontend subnet.");
Assert.assertTrue(expected.getMessage().contains("postgres-db"));
}
}
// ==========================================================================
// CLI COMMANDS FOR DIAGNOSING DOCKER NETWORK TOPOLOGY:
// ==========================================================================
// 1. Inspect containers attached to frontend subnet:
// $ docker network inspect frontend-mesh --format '{{json .Containers}}' | jq
//
// 2. Inspect containers attached to backend private subnet:
// $ docker network inspect backend-data-mesh --format '{{json .Containers}}' | jq
//
// 3. Test DNS resolution from inside a running container:
// $ docker exec -it mesh-test-runner getent hosts api-gateway
// ==========================================================================
}
DOCKER COMPOSE TEST MESH SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬βββββββββββββββββββββββββββββββββ
β DIRECTIVE / KEYWORD β SYNTAX EXAMPLE β WORKFLOW SCOPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌβββββββββββββββββββββββββββββββββ€
β bridge Network β networks: { mesh: { bridge } β Compose Network β Custom isolated container net β
β internal: true β internal: true β Compose Network β Blocks outbound internet I/O β
β Dual-Homed Container β networks: [front, back] β Service Def β Bridges two segregated subnets β
β Static Subnet Config β ipam: { subnet: 172.30.1.0/24β Network IPAM β Explicit predictable IP blocks β
β DNS Service Discovery β http://api-gateway:8080 β Test Config β Inter-container communication β
β depends_on (healthy) β condition: service_healthy β Service Def β Enforces startup dependency β
β healthcheck Directive β test: ["CMD", "wget", ..] β Service Def β Probes container readiness β
β Host Volume Mount β ./target:/app/target β Compose Volume β Extracts test artifacts to hostβ
β W3C Trace Context β traceparent: 00-traceid-... β REST Assured Fltrβ Distributed trace correlation β
β non-root Execution β USER sdet-tester β Dockerfile β Least-privilege container sec β
β --abort-on-container-.. β up --abort-on-container-exit β Compose CLI β Shuts down mesh on test exit β
β Teardown Cleanup β docker compose down -v β Teardown Script β Reclaims memory & volumes β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄βββββββββββββββββββββββββββββββββ€
β TOP 5 DOCKER COMPOSE TEST MESH BEST PRACTICES: β
β 1. Segment networks across tiers: Separate public gateway traffic from private databases and caches. β
β 2. Enforce internal: true on backend networks: Prevent sensitive test dependencies from accessing web. β
β 3. Use cascading healthcheck dependencies: Ensure databases and mocks finish booting before tests start. β
β 4. Inject W3C Trace Context headers: Correlate test requests across gateway, mocks, and logs cleanly. β
β 5. Mount target/ directories as host volumes: Preserve Allure results and failure dumps after teardown. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ