CONTAINERIZED REST ASSURED: DOCKER COMPOSE & EPHEMERAL ENVIRONMENTS

Architect containerized test automation ecosystems in REST Assured: Multi-stage Docker builds (Eclipse Temurin JRE & Maven caching), orchestration via Docker Compose, isolated bridge networks (DNS service discovery), spinning ephemeral WireMock and MySQL dependencies, non-root security contexts, and volume mounting test results for CI reporting.

🐳 Containerization, Hermetic Isolation & Ephemeral Test Infrastructure

The classic engineering grievanceβ€”"It works on my local machine, but fails in the CI pipeline or staging cluster"β€”frequently stems from environmental drift: differing JDK patch releases, local Maven caching discrepancies, missing network dependencies, and conflicting host port allocations. Containerized Test Automation solves this by encapsulating the entire execution runtimeβ€”the Java Virtual Machine, Apache Maven, project dependencies, configuration matrices, and REST Assured test suitesβ€”inside lightweight, immutable Docker containers. By orchestrating multi-stage Dockerfiles alongside Docker Compose, automation architects spin up fully self-contained, ephemeral microservice topologies featuring live mock servers (WireMock), isolated relational databases (MySQL/PostgreSQL), and REST Assured test runner containers communicating over private bridge networks via internal DNS. Once tests finish, volume-mounted artifacts (Allure results and failure dumps) are extracted seamlessly back to the host system before the environment is cleanly destroyed.

1. Containerized Test Automation & Docker Bridge Network Topography
The architectural network topology of a containerized REST Assured ecosystem, illustrating how test runners, target API microservices, mock backends, and databases communicate through isolated internal Docker network bridges via DNS service discovery.
Docker Compose Microservice & Test Runner Topography
ISOLATED DOCKER BRIDGE NETWORK: "automation-mesh" (172.28.0.0/16)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CONTAINER: rest-assured-runner (Ephemeral Test Container)                                     β”‚
β”‚ Base Image: eclipse-temurin:17-jre-alpine                                                     β”‚
β”‚ Execution: mvn test -Denv=docker -DsuiteXmlFile=testng-ci.xml                                 β”‚
β”‚ Shared Volume: ./target/allure-results:/app/target/allure-results (Host Mount)                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β–Ό (HTTP / TLS Port 8080)   β–Ό (JDBC Port 3306)         β–Ό (HTTP Port 8080)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CONTAINER: mock-wiremock     β”‚ β”‚ CONTAINER: mysql-db          β”‚ β”‚ CONTAINER: api-gateway       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Service DNS: "wiremock"      β”‚ β”‚ Service DNS: "mysql-db"      β”‚ β”‚ Service DNS: "api-gateway"   β”‚
β”‚ Port: 8080                   β”‚ β”‚ Port: 3306                   β”‚ β”‚ Port: 8080                   β”‚
β”‚ Image: wiremock/wiremock     β”‚ β”‚ Image: mysql:8.0             β”‚ β”‚ Image: internal-app/api:v1   β”‚
β”‚ Simulates payment gateway &  β”‚ β”‚ Ephemeral in-memory database β”‚ β”‚ Target enterprise SUT micro- β”‚
β”‚ third-party auth services    β”‚ β”‚ initialized via init.sql     β”‚ β”‚ service under direct test    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Build Execution Completes / Zero Residual State)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ HOST SYSTEM EXTRACTION: docker-compose down -v                                                β”‚
β”‚  β”œβ”€β”€ Containers terminated and memory buffers reclaimed                                       β”‚
β”‚  └── Allure results and failure logs persist on host in ./target/allure-results for reporting β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Never configure test containers to connect to "localhost". Inside a Docker network bridge, "localhost" resolves strictly to the test container's own internal loopback interface. Always address neighboring service containers using their declared Docker Compose service names (e.g., http://api-gateway:8080 or http://wiremock:8080) via Docker's embedded DNS server.
Real-Time Example 1: Multi-Stage Production Dockerfile for REST Assured
Authoring an optimized, multi-stage Dockerfile. Stage 1 (Builder) caches Maven dependencies using dependency:go-offline; Stage 2 (Runner) creates a lean, secure execution container using non-root permissions and Eclipse Temurin JRE.
Dockerfile (Multi-Stage Build in Repository Root)
# ==============================================================================
# STAGE 1: DEPENDENCY CACHING & BUILD ENVIRONMENT
# ==============================================================================
FROM maven:3.9.6-eclipse-temurin-17-alpine AS build-cache

WORKDIR /app

# Copy only pom.xml first to leverage Docker layer caching for dependencies
COPY pom.xml .

# Download dependencies offline (Cached unless pom.xml changes)
RUN mvn dependency:go-offline -B

# Copy project source code and test assets
COPY src ./src

# Compile test classes without executing tests during the image build phase
RUN mvn test-compile -B

# ==============================================================================
# STAGE 2: PRODUCTION TEST EXECUTION CONTAINER
# ==============================================================================
FROM maven:3.9.6-eclipse-temurin-17-alpine AS test-runner

WORKDIR /app

# Security Best Practice: Create non-root automation user and group
RUN addgroup -S qa-automation && adduser -S sdet-tester -G qa-automation

# Copy cached Maven local repository and compiled artifacts from build stage
COPY --from=build-cache /root/.m2 /home/sdet-tester/.m2
COPY --from=build-cache /app /app

# Ensure non-root ownership of workspace and home directories
RUN chown -R sdet-tester:qa-automation /app /home/sdet-tester/.m2

# Switch to unprivileged execution user
USER sdet-tester

# Global environment defaults for containerized execution
ENV MAVEN_CONFIG=/home/sdet-tester/.m2
ENV MAVEN_OPTS="-Xms512m -Xmx1536m"
ENV env=docker

# Declare mount points for test results and failure dumps
VOLUME ["/app/target/allure-results", "/app/target/failure-dumps"]

# Entrypoint dispatches test execution dynamically via parameters
ENTRYPOINT ["mvn", "test"]
CMD ["-Denv=docker", "-DsuiteXmlFile=src/test/resources/testng-parallel-suite.xml"]
Dockerfile Optimization Highlights: 1. Multi-Stage Layering: dependency:go-offline caches third-party JARs; rebuilding images when only test code changes takes seconds instead of re-downloading dependencies. 2. Least Privilege Security: Executes as non-root user 'sdet-tester', adhering to CIS Docker benchmark standards for container security. 3. Explicit VOLUME Declarations: Ensures test execution output and Allure raw data write cleanly to mounted host volumes.
Real-Time Example 2: Docker Compose Orchestration Matrix (docker-compose.yml)
Orchestrating an end-to-end multi-container test ecosystem via docker-compose.yml. Spawns an ephemeral MySQL database, a WireMock virtualization server, and links the REST Assured test runner across an isolated network bridge.
YAML (docker-compose.yml Microservice Topology)
version: '3.8'

networks:
  automation-mesh:
    driver: bridge
    ipam:
      config:
        - subnet: 172.28.0.0/16

services:
  # ============================================================================
  # SERVICE 1: EPHEMERAL MOCK SERVER (WireMock)
  # ============================================================================
  wiremock:
    image: wiremock/wiremock:3.5.2-alpine
    container_name: mock-wiremock-service
    networks:
      - automation-mesh
    ports:
      - "8089:8080"
    volumes:
      - ./src/test/resources/mappings:/home/wiremock/mappings
      - ./src/test/resources/__files:/home/wiremock/__files
    command: ["--global-response-templating", "--verbose"]
    healthcheck:
      test: ["CMD", "nc", "-z", "localhost", "8080"]
      interval: 3s
      timeout: 3s
      retries: 5

  # ============================================================================
  # SERVICE 2: EPHEMERAL DATABASE (MySQL 8.0)
  # ============================================================================
  mysql-db:
    image: mysql:8.0.36
    container_name: ephemeral-mysql-db
    networks:
      - automation-mesh
    environment:
      MYSQL_ROOT_PASSWORD: RootSecret#2026
      MYSQL_DATABASE: enterprise_masterclass
      MYSQL_USER: sdet_tester
      MYSQL_PASSWORD: TestPass#2026
    ports:
      - "3307:3306"
    volumes:
      - ./src/test/resources/sql/init-schema.sql:/docker-entrypoint-initdb.d/init.sql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "sdet_tester", "-pTestPass#2026"]
      interval: 4s
      timeout: 4s
      retries: 10

  # ============================================================================
  # SERVICE 3: REST ASSURED TEST RUNNER CONTAINER
  # ============================================================================
  rest-assured-runner:
    build:
      context: .
      dockerfile: Dockerfile
      target: test-runner
    container_name: rest-assured-test-runner
    networks:
      - automation-mesh
    depends_on:
      wiremock:
        condition: service_healthy
      mysql-db:
        condition: service_healthy
    environment:
      - env=docker
      - API_BASE_URL=http://wiremock:8080
      - DB_URL=jdbc:mysql://mysql-db:3306/enterprise_masterclass?useSSL=false&allowPublicKeyRetrieval=true
      - DB_USER=sdet_tester
      - DB_PASS=TestPass#2026
    volumes:
      - ./target/allure-results:/app/target/allure-results
      - ./target/failure-dumps:/app/target/failure-dumps
Compose Orchestration Flow: 1. depends_on with service_healthy: The test runner waits until MySQL finishes initializing tables and WireMock responds to health checks before dispatching tests. 2. Volume Mapping: ./target/allure-results maps directly to host storage, allowing Allure to render reports on the host after containers shut down.
Real-Time Example 3: Dynamic Docker Environment Configuration via OWNER Properties
Integrating Docker environment overrides with the OWNER configuration library. Configures docker.properties in src/test/resources/config/ to resolve hostnames like wiremock:8080 and mysql-db:3306 via container DNS.
Properties (src/test/resources/config/docker.properties)
# ==============================================================================
# CONFIGURATION PROFILE: DOCKER CONTAINERIZED ENVIRONMENT
# Loaded automatically by OWNER via -Denv=docker or ENV=docker
# ==============================================================================
api.base.url=http://wiremock:8080
api.base.path=/v1
api.timeout.ms=8000
api.logging.enabled=true

# Database Connectivity via Internal Docker DNS
db.url=jdbc:mysql://mysql-db:3306/enterprise_masterclass?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
db.user=sdet_tester
db.password=TestPass#2026

# Virtualization Endpoints
auth.server.url=http://wiremock:8080
auth.client.id=docker-automation-runner
auth.client.secret=DockerSecret#Key2026
tenant.region=MH-PUNE-DOCKER-NODE
Java (Test Demonstrating Internal Container DNS Resolution)
package com.nikita.restassured.docker;

import com.nikita.restassured.config.ConfigFactoryManager;
import com.nikita.restassured.config.EnvironmentConfig;
import io.restassured.http.ContentType;
import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class ContainerDnsVerificationTest {

    @Test(description = "Verify REST Assured resolves internal container DNS hostnames within Docker network bridge")
    public void testInternalContainerDnsResolution() {
        EnvironmentConfig config = ConfigFactoryManager.getConfig();

        System.out.println("[*] Executing inside container environment: " + config.targetEnvironment());
        System.out.println("[*] Target API Hostname : " + config.apiBaseUrl());

        // Assert hostname uses Docker service discovery name, not localhost
        if ("docker".equalsIgnoreCase(config.targetEnvironment())) {
            Assert.assertTrue(config.apiBaseUrl().contains("wiremock"), 
                    "Inside Docker, base URL must resolve to service hostname 'wiremock'!");
        }

        given()
            .baseUri(config.apiBaseUrl())
            .basePath(config.apiBasePath())
            .contentType(ContentType.JSON)
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"))
            .body("data.id", equalTo("STU-88219"));

        System.out.println("[βœ”] Successfully communicated with companion container via Docker bridge DNS.");
    }
}
Container DNS Telemetry: [*] Executing inside container environment: docker [*] Target API Hostname : http://wiremock:8080 Resolved wiremock ──► 172.28.0.2 via embedded Docker DNS (127.0.0.11:53) GET http://wiremock:8080/v1/students/STU-88219 -> HTTP 200 OK [14ms] PASSED: testInternalContainerDnsResolution
Real-Time Example 4: Automating Docker Lifecycle via Shell Runner Script (run-tests.sh)
Encapsulating the container test lifecycle into an executable bash script. Manages building images, spinning up compose services, waiting for healthy containers, capturing test exit codes, and cleaning up environments.
Bash (run-tests.sh Automated Container Lifecycle Script)
#!/usr/bin/env bash
# ==============================================================================
# SCRIPT: run-tests.sh
# Purpose: Orchestrates complete build, execution, artifact extraction, and teardown
# ==============================================================================
set -e # Exit immediately on error

echo "=============================================================================="
echo "  STARTING DOCKER CONTAINERIZED REST ASSURED TEST ECOSYSTEM"
echo "=============================================================================="

# Ensure output directories exist on host system prior to mounting
mkdir -p target/allure-results target/failure-dumps target/allure-report

# Step 1: Clean up any stale containers or volumes from prior runs
echo "[*] Cleaning up stale containers..."
docker-compose down -v --remove-orphans

# Step 2: Build the test runner container image
echo "[*] Building REST Assured test runner image..."
docker-compose build rest-assured-runner

# Step 3: Run the test suite and capture the exit code
echo "[*] Launching containerized test execution..."
# Set exit code trap so teardown always runs
set +e
docker-compose up --abort-on-container-exit --exit-code-from rest-assured-runner
TEST_EXIT_CODE=$?
set -e

echo "=============================================================================="
echo "  TEST EXECUTION COMPLETED WITH EXIT CODE: ${TEST_EXIT_CODE}"
echo "=============================================================================="

# Step 4: Gracefully tear down infrastructure
echo "[*] Tearing down ephemeral containers..."
docker-compose down -v

# Step 5: Check if Allure results were generated on host
ALLURE_FILES_COUNT=$(ls -1 target/allure-results/*.json 2>/dev/null | wc -l || echo 0)
echo "[*] Host Artifacts Extracted: ${ALLURE_FILES_COUNT} Allure result files found."

if [ $TEST_EXIT_CODE -ne 0 ]; then
    echo "[-] ERROR: REST Assured test suite reported failures! Check target/failure-dumps/"
    exit $TEST_EXIT_CODE
else
    echo "[+] SUCCESS: All containerized API tests verified cleanly."
    exit 0
fi
Script Execution Output: $ ./run-tests.sh [*] Cleaning up stale containers... [*] Building REST Assured test runner image... [*] Launching containerized test execution... Starting ephemeral-mysql-db ... done Starting mock-wiremock-service ... done Attaching to rest-assured-test-runner [INFO] Tests run: 450, Failures: 0, Errors: 0, Skipped: 0 rest-assured-test-runner exited with code 0 [*] Tearing down ephemeral containers... [*] Host Artifacts Extracted: 450 Allure result files found. [+] SUCCESS: All containerized API tests verified cleanly.
Real-Time Example 5: Integrating Containerized Runs into GitHub Actions
Running containerized test suites in continuous integration. Demonstrates executing docker-compose within a GitHub Actions workflow step, harvesting volume-mounted test artifacts, and compiling Allure reports on the host runner.
YAML (.github/workflows/docker-api-tests.yml)
name: Containerized API Regression (Docker Compose)

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  docker-test-execution:
    name: Run Tests inside Ephemeral Docker Compose 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: Create Artifact Host Directories
        run: |
          mkdir -p target/allure-results target/failure-dumps
          chmod -R 777 target/ # Ensure non-root container can write to mounted host dirs

      - name: Execute Containerized Test Suite via Docker Compose
        run: |
          docker compose up \
            --build \
            --abort-on-container-exit \
            --exit-code-from rest-assured-runner

      - name: Teardown Docker Containers
        if: always()
        run: docker compose down -v

      - name: Upload Failure Diagnostics
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: docker-failure-dumps
          path: target/failure-dumps/*.log
          retention-days: 14

      - name: Upload Allure Results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: docker-allure-results
          path: target/allure-results/
          retention-days: 7
CI Container Telemetry: Docker Buildx: Built test-runner layer cache in 18s Containers started: ephemeral-mysql-db, mock-wiremock-service, rest-assured-test-runner All tests executed inside isolated container mesh. Target artifacts mapped to GitHub Actions runner and uploaded cleanly.
Real-Time Example 6: Initializing Ephemeral MySQL Databases via init-schema.sql
Seeding fresh relational databases on container boot. Uses Docker's entrypoint initialization directory (/docker-entrypoint-initdb.d/) to execute SQL schema creation and seed baseline reference records before tests start.
SQL (src/test/resources/sql/init-schema.sql)
-- ==============================================================================
-- DATABASE INITIALIZATION SCRIPT: init-schema.sql
-- Mounted into container at: /docker-entrypoint-initdb.d/init.sql
-- Executed automatically on container boot before accepting connections
-- ==============================================================================

USE enterprise_masterclass;

DROP TABLE IF EXISTS students;

CREATE TABLE students (
    student_id VARCHAR(64) PRIMARY KEY,
    full_name VARCHAR(150) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    academic_track VARCHAR(80) NOT NULL,
    enrolled_credits INT NOT NULL DEFAULT 0,
    status VARCHAR(30) NOT NULL DEFAULT 'ACTIVE',
    tenant_id VARCHAR(50) NOT NULL DEFAULT 'MH-PUNE-DOCKER-NODE',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Seed prerequisite test baseline records
INSERT INTO students (student_id, full_name, email, academic_track, enrolled_credits, status)
VALUES
('STU-88219', 'Nikita Sharma', 'nikita.sharma@nikita-infotech.com', 'ENTERPRISE_AUTOMATION', 16, 'ACTIVE'),
('STU-88220', 'Aarav Deshmukh', 'aarav.deshmukh@nikita-infotech.com', 'FULLSTACK_SDET', 12, 'ACTIVE');
Database Initialization Telemetry: MySQL container boots -> Executes /docker-entrypoint-initdb.d/init.sql Table 'students' created with UTF8MB4 character set. Baseline records STU-88219 and STU-88220 seeded. Container health check passes; ready for REST Assured tests.
Real-Time Example 7: Containerized Two-Phase Verification: Wire API vs. Container MySQL
Executing end-to-end reconciliation inside containers. A REST Assured test running in container A dispatches an HTTP request to WireMock in container B, then queries MySQL in container C over the internal Docker network bridge to reconcile persistent state.
Java (DockerTwoPhaseReconciliationTest.java)
package com.nikita.restassured.docker;

import com.nikita.restassured.config.ConfigFactoryManager;
import com.nikita.restassured.config.EnvironmentConfig;
import com.nikita.restassured.database.DatabaseManager;
import io.restassured.http.ContentType;
import org.assertj.core.api.Assertions;
import org.testng.annotations.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class DockerTwoPhaseReconciliationTest {

    @Test(description = "Verify two-phase state reconciliation across distinct container boundaries")
    public void testCrossContainerStateReconciliation() throws SQLException {
        EnvironmentConfig config = ConfigFactoryManager.getConfig();

        String targetStudentId = "STU-88219";

        // -------------------------------------------------------------
        // PHASE 1: HTTP WIRE QUERY ACROSS DOCKER BRIDGE TO WIREMOCK
        // -------------------------------------------------------------
        given()
            .baseUri(config.apiBaseUrl())
            .basePath(config.apiBasePath())
            .contentType(ContentType.JSON)
            .pathParam("id", targetStudentId)
        .when()
            .get("/students/{id}")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"))
            .body("data.id", equalTo(targetStudentId));

        System.out.println("[Phase 1 Pass] HTTP wire response received from mock container.");

        // -------------------------------------------------------------
        // PHASE 2: DIRECT JDBC QUERY ACROSS DOCKER BRIDGE TO MYSQL
        // -------------------------------------------------------------
        String sql = "SELECT full_name, academic_track, enrolled_credits FROM students WHERE student_id = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, targetStudentId);

            try (ResultSet rs = stmt.executeQuery()) {
                Assertions.assertThat(rs.next())
                        .as("Record must exist in containerized MySQL table")
                        .isTrue();

                String fullName = rs.getString("full_name");
                String track = rs.getString("academic_track");
                int credits = rs.getInt("enrolled_credits");

                Assertions.assertThat(fullName).isEqualTo("Nikita Sharma");
                Assertions.assertThat(track).isEqualTo("ENTERPRISE_AUTOMATION");
                Assertions.assertThat(credits).isEqualTo(16);

                System.out.printf("[Phase 2 Pass] Reconciled container DB record: %s | Track: %s | Credits: %d%n",
                        fullName, track, credits);
            }
        }
    }
}
Cross-Container Execution Output: [Phase 1 Pass] HTTP wire response received from mock container. [Phase 2 Pass] Reconciled container DB record: Nikita Sharma | Track: ENTERPRISE_AUTOMATION | Credits: 16 PASSED: testCrossContainerStateReconciliation Demonstrates full inter-container networking without host port dependencies.
Real-Time Example 8: Debugging Docker Networking Pitfalls & File Permission Triage
Troubleshooting common containerization pitfalls: resolving java.net.ConnectException: Connection refused caused by localhost confusion, fixing Linux permission denials on mounted volumes, and managing slow container health checks.
Java & Bash (Triage: Diagnosing Connection Refused & Permission Denied)
// ==============================================================================
// PITFALL 1: ConnectException: Connection refused (localhost vs. Service Name)
// Symptom: Test inside container fails with:
// java.net.ConnectException: Connection refused: localhost:8080
//
// CAUSE: Code used "http://localhost:8080". Inside container A, "localhost"
// refers to container A itself, NOT neighboring containers!
//
// FIX: Always use the Docker service name declared in docker-compose.yml:
// "http://wiremock:8080" or "http://api-gateway:8080"
// ==============================================================================

// ==============================================================================
// PITFALL 2: Permission denied ON MOUNTED VOLUME WRITE
// Symptom: Inside container, Maven fails with:
// java.io.FileNotFoundException: target/allure-results/... (Permission denied)
//
// CAUSE: The host directory (target/allure-results) is owned by root or host user,
// but the Docker container runs as non-root user 'sdet-tester' (UID 1000/1001).
//
// FIX: On the host machine before launching docker compose, run:
// $ mkdir -p target/allure-results target/failure-dumps && chmod -R 777 target/
// OR align the UID in the Dockerfile with the host user!
// ==============================================================================

// ==============================================================================
// PITFALL 3: TEST RUNNER STARTS BEFORE DATABASE IS READY
// Symptom: Tests fail immediately on first JDBC call with Communications link failure.
//
// CAUSE: MySQL container was still booting and initializing tables.
//
// FIX: Use Docker Compose 'depends_on' with 'condition: service_healthy'
// and define an explicit 'mysqladmin ping' health check!
// ==============================================================================
Triage Diagnostic Breakdown: - Connection Refused: Resolved by configuring docker.properties with container DNS names (wiremock, mysql-db). - Volume Permission Denied: Resolved by pre-creating target/ directories with write permissions on host. - Race Condition on Boot: Resolved by enforcing service_healthy checks before test container starts.
Real-Time Example 9: Docker Containerization Reference Matrix
A comprehensive reference summary pairing Docker directives, Compose configuration options, networking rules, and operational best practices for containerized REST Assured test automation.
Docker Containerization Specification Reference Matrix
DOCKER CONTAINERIZATION SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ DOCKER DIRECTIVE / KEY  β”‚ SYNTAX EXAMPLE               β”‚ SCOPE LEVEL      β”‚ PRIMARY OPERATIONAL PURPOSE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Multi-Stage Build       β”‚ FROM maven:3.9 AS build      β”‚ Dockerfile       β”‚ Caches dependencies cleanly   β”‚
β”‚ Non-Root User           β”‚ USER sdet-tester             β”‚ Dockerfile       β”‚ Security least-privilege guardβ”‚
β”‚ VOLUME Mount            β”‚ VOLUME ["/app/target/..."]   β”‚ Dockerfile       β”‚ Declares persistence mounts   β”‚
β”‚ bridge Network          β”‚ networks: automation-mesh    β”‚ Compose Network  β”‚ Private container DNS network β”‚
β”‚ service_healthy         β”‚ condition: service_healthy   β”‚ Compose depends_onBlocks test until DB is ready  β”‚
β”‚ Healthcheck Test        β”‚ test: ["CMD", "mysqladmin"]  β”‚ Compose Service  β”‚ Probes port/service readiness β”‚
β”‚ Port Mapping            β”‚ "8089:8080" (Host:Container) β”‚ Compose Service  β”‚ Exposes port to host developerβ”‚
β”‚ Volume Mapping          β”‚ ./target:/app/target         β”‚ Compose Volume   β”‚ Extracts test results to host β”‚
β”‚ Internal DNS Hostname   β”‚ http://wiremock:8080         β”‚ Test Config      β”‚ Inter-container communication β”‚
β”‚ dependency:go-offline   β”‚ RUN mvn dependency:go-offlineβ”‚ Docker Build     β”‚ Pre-fetches dependencies      β”‚
β”‚ docker-compose down -v  β”‚ docker-compose down -v       β”‚ Teardown Script  β”‚ Cleans containers & volumes   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 DOCKER TEST CONTAINERIZATION BEST PRACTICES:                                                        β”‚
β”‚ 1. Never connect to localhost across containers: Use Docker service names (http://wiremock:8080).         β”‚
β”‚ 2. Use multi-stage Docker builds: Cache ~/.m2 dependencies to accelerate image build times.               β”‚
β”‚ 3. Enforce service_healthy conditions: Wait for databases and mock servers to complete initialization.    β”‚
β”‚ 4. Run containers as non-root users: Follow container security best practices for CI/CD environments.     β”‚
β”‚ 5. Mount ./target as a host volume: Ensure Allure results and failure dumps persist after teardown.       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Containerizing REST Assured with Docker and Docker Compose eliminates "it works on my machine" inconsistencies. By orchestrating multi-stage Docker builds, private bridge networks, healthy service dependencies, and volume-mounted artifact extraction, you establish reproducible, self-contained test ecosystems that execute reliably on developer workstations, Jenkins agents, and GitHub Actions runners alike.