DOCKER COMPOSE TEST MESH: MULTI-SERVICE VIRTUALIZATION & NETWORKING

Architect segmented multi-service container mesh environments for REST Assured: Subnet partitioning across public and database tiers, multi-instance WireMock virtualization (Auth, Payment, Notification), Redis and RabbitMQ ephemeral sidecars, custom healthcheck dependency cascades, inter-container trace correlation, and automated test mesh teardown.

πŸ•ΈοΈ 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.

1. Multi-Tier Dual-Homed Network Mesh Architecture
The architectural network topology of an enterprise Docker Compose Test Mesh, showcasing dual-homed network segregation where the API Gateway bridges the public frontend network with secure private data tiers.
Dual-Homed Docker Network Mesh Subnet Topography
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!
Architectural Standard: Network segregation via dual-homed bridges mirrors enterprise Kubernetes topologies. By isolating backend databases and caching layers onto a dedicated private data subnet, tests verify that the public API Gateway correctly guards private infrastructure from unauthorized direct access.
Real-Time Example 1: Enterprise Multi-Service docker-compose.mesh.yml
A comprehensive, multi-container Compose specification. Spawns an API Gateway, PostgreSQL database, Redis distributed cache, RabbitMQ message broker, WireMock downstream simulator, and the REST Assured test runner across two segregated subnets.
YAML (docker-compose.mesh.yml Multi-Tier Definition)
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
Mesh Network Features: 1. Segregated Networks: frontend-mesh hosts the runner and public gateway; backend-data-mesh hosts databases, cache, and mocks. 2. internal: true: Disallows internet routing out of backend-data-mesh, ensuring zero data exfiltration risks. 3. Cascading Health Dependencies: The runner starts only when api-gateway is ready, which in turn waits for WireMock, Redis, and Postgres.
Real-Time Example 2: API Gateway Routing & Proxy Configuration (gateway.conf)
Configuring the internal API Gateway reverse proxy. Maps inbound HTTP requests to downstream WireMock and mock services, enforces request header forwarding, and exposes health probes.
Nginx Config (src/test/resources/mesh/nginx/gateway.conf)
# ==============================================================================
# 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";
    }
}
Gateway Verification: Inbound requests to http://api-gateway:8080/v1/students receive the X-Gateway-Routed: true header and are reverse-proxied to mock-wiremock:8080 over the private backend-data-mesh network.
Real-Time Example 3: Initializing PostgreSQL Schema & Seed Data (init-postgres.sql)
Automating schema provisioning on container boot. Configures relational tables, triggers, and baseline records in PostgreSQL, ensuring the ephemeral database container starts fully initialized.
SQL (src/test/resources/mesh/sql/init-postgres.sql)
-- ==============================================================================
-- 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;
Postgres Boot Telemetry: Connected to database masterclass_db as user sdet_admin. Table academic.students created with TIMESTAMPTZ audit columns. Baseline student records STU-88219, STU-88220, and STU-77100 seeded. Healthcheck pg_isready returns exit code 0.
Real-Time Example 4: Distributed W3C Trace Context & Correlation Filter
Implementing distributed tracing across the container mesh. Builds a REST Assured filter that injects W3C Trace Context (traceparent) and X-Correlation-Id headers to trace requests as they traverse the gateway and mock services.
Java (MeshCorrelationFilter.java Distributed Tracing Interceptor)
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;
    }
}
Trace Context Telemetry: Outbound Request Headers: β€’ X-Correlation-Id: CORR-MESH-24-4f8a10c9 β€’ traceparent: 00-a1b2c3d4e5f60718293a4b5c6d7e8f90-1234567890abcdef-01 Round-trip logged: GET http://api-gateway:8080/v1/students/STU-88219 -> HTTP 200 OK (18ms)
Real-Time Example 5: End-to-End Test Suite Running Inside the Docker Mesh
Authoring a complete REST Assured test suite designed for the container mesh. Validates gateway routing, asserts reverse-proxy header preservation, checks WireMock mock responses, and verifies end-to-end trace correlation.
Java (DockerMeshIntegrationTest.java Test Suite)
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.");
    }
}
Test Execution Telemetry: [*] DockerMeshIntegrationTest initialized against gateway: http://api-gateway:8080 [MESH TRACE] GET http://api-gateway:8080/health βž” HTTP 200 (12 ms) [βœ”] Gateway health check verified: All mesh dependencies are UP. [MESH TRACE] GET http://api-gateway:8080/v1/students/STU-88219 βž” HTTP 200 (22 ms) [βœ”] Student query successfully traversed the API Gateway mesh to WireMock. [MESH TRACE] POST http://api-gateway:8080/v1/payments βž” HTTP 200 (28 ms) [βœ”] Payment payload routed successfully across the container mesh. PASSED: 3/3 mesh routing scenarios executed cleanly inside container network.
Real-Time Example 6: Orchestration Lifecycle Shell Script (launch-mesh.sh)
An automated shell runner script for the test mesh. Manages spinning up Docker Compose services, probing container health, executing the REST Assured test runner, harvesting test artifacts, and performing a clean volume teardown.
Bash (launch-mesh.sh Automated Mesh Orchestrator)
#!/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
Script Execution Output: $ ./launch-mesh.sh [*] Cleaning up orphaned containers and networks... [*] Building REST Assured runner image... [*] Spinning up mesh dependencies... Creating mesh-mock-wiremock ... done Creating mesh-redis-cache ... done Creating mesh-postgres-db ... done Creating mesh-api-gateway ... done [*] Waiting for API Gateway and upstream services to become healthy... ... [+] API Gateway is HEALTHY. All upstream mesh nodes operational. [*] Executing REST Assured test suite inside mesh runner... [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 mesh-test-runner exited with code 0 [*] Tearing down test mesh infrastructure... Removing mesh-test-runner ... done Removing mesh-api-gateway ... done Removing mesh-postgres-db ... done Removing mesh-redis-cache ... done Removing mesh-mock-wiremock ... done Removing network frontend-mesh Removing network backend-data-mesh [+] SUCCESS: All containerized mesh tests passed cleanly.
Real-Time Example 7: CI/CD Integration via GitHub Actions (.github/workflows/mesh-ci.yml)
Running the Docker Compose Test Mesh inside GitHub Actions. Leverages Docker Compose to orchestrate multi-container dependencies, harvests volume-mounted Allure results, and deploys the report dashboard seamlessly.
YAML (.github/workflows/mesh-ci.yml GitHub Actions Pipeline)
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
CI Pipeline Execution Summary: 1. Docker Buildx initializes layer cache. 2. launch-mesh.sh spins up Postgres, Redis, WireMock, and Nginx Gateway. 3. Tests execute within the isolated container network. 4. Results harvested from mounted ./target volume and published as CI build artifacts.
Real-Time Example 8: Debugging Network Segregation & Subnet Isolation Triage
Troubleshooting network segregation and container connectivity defects: diagnosing UnknownHostException on segregated subnets, inspecting Docker bridge routes via docker network inspect, and verifying firewall boundary enforcement.
Java & CLI (Triage: Diagnosing Subnet Isolation & DNS Failures)
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
    // ==========================================================================
}
Triage Diagnostic Breakdown: - Subnet Isolation Verification: Attempting to resolve 'postgres-db' from the runner throws UnknownHostException. - Root Cause: Container sits strictly on frontend-mesh; backend-data-mesh is isolated. - Security Audit: Confirms that network boundaries function as intended, preventing direct access to private data tiers.
Real-Time Example 9: Docker Compose Test Mesh Specification Reference Matrix
A comprehensive reference summary pairing Docker Compose networking directives, service discovery principles, healthcheck parameters, and operational best practices for containerized API test mesh automation.
Docker Compose Test Mesh Specification Reference Matrix
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.    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: The Docker Compose Test Mesh establishes a hermetic, production-like test environment on any machine. By combining dual-homed bridge networks, multi-service dependency health checks, WireMock service virtualization, and distributed W3C trace correlation, you build reliable, isolated API automation suites that validate complex microservice interactions with complete consistency across workstations and CI/CD runners.