Settings Properties

Note: configuration properties loaded from property files and environment variables are read once at startup and cached. Changes to property files or environment variables after MockServer has started will not take effect. To change configuration at runtime, use the REST API (PUT /mockserver/configuration) or programmatic ConfigurationProperties method calls. System property changes via ConfigurationProperties static methods are read dynamically for properties that support runtime changes (e.g., logLevel).

Properties can be set by:

  1. java code (highest precedence)
  2. @MockServerTest annotation (per-instance Configuration object)
  3. system property
  4. property file
  5. environment variable (lowest precedence)

The order of precedence means that properties set by java code overrides those set by @MockServerTest which overrides system properties which overrides property file properties which overrides environment variables.

When using @MockServerTest, properties prefixed with mockserver. (e.g. mockserver.initializationClass=...) are applied to the per-instance Configuration object, not to global system properties. This makes them safe for parallel test execution.

Some properties need to be set before MockServer starts because they are only read at start-up, for example, nioEventLoopThreadCount.

Other values are read continuously and so can be changed at any time, for example, logLevel.

 

Programmatic Properties

There are two ways to set properties programmatically, as follows:

  • org.mockserver.configuration.ConfigurationProperties
    • is JVM global
    • exposes static methods
    • stores property values in system properties
  • org.mockserver.configuration.Configuration
    • is unique to each MockServer instance
    • can be passed to ClientAndServer, MockServer and MockServerClient classes
    • only supports instance methods
    • defaults to ConfigurationProperties for unset values
 

Property File

The property file defaults to filename mockserver.properties in the current working directory of MockServer.

This location of the property file can be changed by setting the mockserver.propertyFile system property or MOCKSERVER_PROPERTY_FILE environment property, for example:

-Dmockserver.propertyFile=/config/mockserver.properties

A full example / template properties file can be found in github

An limited properties file example is, as follows:

###############################
# MockServer & Proxy Settings #
###############################

# Socket & Port Settings

# socket timeout in milliseconds (default 20000)
mockserver.maxSocketTimeout=20000

# Certificate Generation

# dynamically generated CA key pair (if they don't already exist in specified directory)
mockserver.dynamicallyCreateCertificateAuthorityCertificate=true
# save dynamically generated CA key pair in working directory
mockserver.directoryToSaveDynamicSSLCertificate=.
# certificate domain name (default "localhost")
mockserver.sslCertificateDomainName=localhost
# comma separated list of ip addresses for Subject Alternative Name domain names (default empty list)
mockserver.sslSubjectAlternativeNameDomains=www.example.com,www.another.com
# comma separated list of ip addresses for Subject Alternative Name ips (default empty list)
mockserver.sslSubjectAlternativeNameIps=127.0.0.1

# CORS

# enable CORS for MockServer REST API
mockserver.enableCORSForAPI=true
# enable CORS for all responses
mockserver.enableCORSForAllResponses=true
 

JSON Configuration File

MockServer also supports configuration via a JSON file. To use a JSON configuration file, set the mockserver.propertyFile system property or MOCKSERVER_PROPERTY_FILE environment variable to a file path ending with .json, for example:

-Dmockserver.propertyFile=/config/mockserver.json

The JSON format uses camelCase property names without the mockserver. prefix. An example JSON configuration file:

{
  "logLevel": "INFO",
  "maxSocketTimeout": 120000,
  "dynamicallyCreateCertificateAuthorityCertificate": true,
  "directoryToSaveDynamicSSLCertificate": ".",
  "sslCertificateDomainName": "localhost",
  "sslSubjectAlternativeNameDomains": ["www.example.com", "www.another.com"],
  "sslSubjectAlternativeNameIps": ["127.0.0.1"],
  "enableCORSForAPI": true,
  "enableCORSForAllResponses": true
}

The JSON property names are the camelCase equivalents of the mockserver.* property names listed below, with the mockserver. prefix removed. For example, mockserver.maxExpectations becomes maxExpectations in JSON. The complete list of supported JSON keys can be obtained by calling GET /mockserver/configuration, which returns all properties with their current values. This output can be saved as a JSON configuration file and reloaded at startup.

 

Configuration Properties

 

Logging & Metrics Configuration:

Quick Reference

Property Purpose Default
logLevelGlobal minimum log levelINFO
disableSystemOutSuppress stdout outputfalse
disableLoggingDisable all logging and event processingfalse
compactLogFormatOne-line summaries instead of full JSON in stdoutfalse
logLevelOverridesPer-type/category log level overrides{}
detailedMatchFailuresInclude per-field match failure reasonstrue
detailedVerificationFailuresInclude per-field diff in verification failurestrue
launchUIForLogLevelDebugAuto-open UI when log level is DEBUGfalse
metricsEnabledPrometheus metrics endpointfalse

The the minimum level of logs to record in the event log and to output to system out (if system out log output is not disabled). The lower the log level the more log entries will be captured, particularly at TRACE level logging.

Type: string Default: INFO

Java Code:

ConfigurationProperties.logLevel(String level)

System Property:

-Dmockserver.logLevel=...

Environment Variable:

MOCKSERVER_LOG_LEVEL=...

Property File:

mockserver.logLevel=...

The log level, which can be TRACE, DEBUG, INFO, WARN, ERROR, OFF, FINEST, FINE, INFO, WARNING, SEVERE

Example:

-Dmockserver.logLevel="DEBUG"

Disable logging to the system output

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableSystemOut(boolean disableSystemOut)

System Property:

-Dmockserver.disableSystemOut=...

Environment Variable:

MOCKSERVER_DISABLE_SYSTEM_OUT=...

Property File:

mockserver.disableSystemOut=...

Example:

-Dmockserver.disableSystemOut="true"

Disable all logging and processing of log events

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableLogging(boolean disableLogging)

System Property:

-Dmockserver.disableLogging=...

Environment Variable:

MOCKSERVER_DISABLE_LOGGING=...

Property File:

mockserver.disableLogging=...

Example:

-Dmockserver.disableLogging="true"

When enabled, log messages written to stdout/SLF4J use a compact single-line format showing summary information (method, path, status code, expectation ID) instead of full JSON-serialized request and response details. This significantly reduces log noise, especially in CI/CD environments or when running many tests.

The dashboard UI, verification, and log retrieval APIs are not affected — they continue to show full details.

Type: boolean Default: false

Java Code:

ConfigurationProperties.compactLogFormat(boolean enable)

System Property:

-Dmockserver.compactLogFormat=...

Environment Variable:

MOCKSERVER_COMPACT_LOG_FORMAT=...

Property File:

mockserver.compactLogFormat=...

Example output comparison:

Verbose (default):

INFO - 50850 returning response:

  {
    "statusCode" : 200,
    "body" : "{\"accessToken\":{...}}"
  }

 for request:

  {
    "method" : "POST",
    "path" : "/oauth2/token",
    "headers" : { ... }
  }

 from expectation:

  a735b798-8aec-4c15-b264-c6d3c93fda1d

Compact:

INFO - 50850 returning response: 200 for request: POST /oauth2/token from expectation: a735b798-8aec-4c15-b264-c6d3c93fda1d

Example:

-Dmockserver.compactLogFormat="true"

Tip: combine with logLevelOverrides for maximum control. For example, enable compact format and suppress startup/shutdown noise:

-Dmockserver.compactLogFormat="true" -Dmockserver.logLevelOverrides='{"SERVER":"WARN"}'

Override the log level for specific categories of log events or individual log message types. This allows fine-grained control over log verbosity without changing the global log level.

Keys can be category group names or individual log message type names. When both are specified, the individual type override takes precedence over the category group override, which takes precedence over the global logLevel.

This setting affects stdout/SLF4J output and the dashboard UI. The internal event log (used for verification) is not affected.

Note: Overrides can only suppress log events that are already captured at the global logLevel. For example, with logLevel=WARN, setting {"EXPECTATION_MATCHED":"INFO"} will not cause INFO-level match events to appear, because they are not generated when the global level is WARN. To see more verbose events for a specific category, first set the global logLevel low enough (e.g., INFO or DEBUG), then use overrides to suppress the noisy categories.

Type: map (JSON object) Default: {} (empty, global logLevel applies to all categories)

Category Groups:

MATCHINGEXPECTATION_MATCHED, EXPECTATION_NOT_MATCHED, NO_MATCH_RESPONSE
REQUEST_LIFECYCLERECEIVED_REQUEST, FORWARDED_REQUEST, EXPECTATION_RESPONSE, TEMPLATE_GENERATED
EXPECTATION_MANAGEMENTCREATED_EXPECTATION, UPDATED_EXPECTATION, REMOVED_EXPECTATION, CLEARED
VERIFICATIONVERIFICATION, VERIFICATION_FAILED, VERIFICATION_PASSED, RETRIEVED
SERVERSERVER_CONFIGURATION, AUTHENTICATION_FAILED, OPENAPI_RESPONSE_VALIDATION_FAILED
GENERALTRACE, DEBUG, INFO, WARN, ERROR, EXCEPTION

Java Code:

ConfigurationProperties.logLevelOverrides(Map<String, String> overrides)

System Property:

-Dmockserver.logLevelOverrides=...

Environment Variable:

MOCKSERVER_LOG_LEVEL_OVERRIDES=...

Property File:

mockserver.logLevelOverrides=...

REST API:

PUT /mockserver/configuration {"logLevelOverrides": {"MATCHING": "WARN", "EXPECTATION_MATCHED": "INFO"}}

Example - suppress per-expectation match failure noise while keeping match successes:

-Dmockserver.logLevelOverrides='{"MATCHING":"WARN","EXPECTATION_MATCHED":"INFO"}'

Example - suppress all matching and expectation management logs:

MOCKSERVER_LOG_LEVEL_OVERRIDES='{"MATCHING":"WARN","EXPECTATION_MANAGEMENT":"WARN"}'

If true (the default) the log event recording that a request matcher did not match will include a detailed reason why each non matching field did not match. See Troubleshooting Matching for how to use this when debugging.

Type: boolean Default: true

Java Code:

ConfigurationProperties.detailedMatchFailures(boolean enable)

System Property:

-Dmockserver.detailedMatchFailures=...

Environment Variable:

MOCKSERVER_DETAILED_MATCH_FAILURES=...

Property File:

mockserver.detailedMatchFailures=...

Example:

-Dmockserver.detailedMatchFailures="false"

If true (the default) verification failure messages will include a detailed diff showing how each recorded request differed from the expected request. This makes it easier to identify why a verification failed by highlighting per-field mismatches between the expected and actual requests.

Disable this if verification failure messages are too verbose or if you prefer concise failure output.

Type: boolean Default: true

Java Code:

ConfigurationProperties.detailedVerificationFailures(boolean enable)

System Property:

-Dmockserver.detailedVerificationFailures=...

Environment Variable:

MOCKSERVER_DETAILED_VERIFICATION_FAILURES=...

Property File:

mockserver.detailedVerificationFailures=...

Example:

-Dmockserver.detailedVerificationFailures="false"

If true (the default) the ClientAndServer constructor or static factor methods will open the UI in the default browser when the log level is set to DEBUG.

Type: string Default: false

Java Code:

ConfigurationProperties.launchUIForLogLevelDebug(boolean enable)

System Property:

-Dmockserver.launchUIForLogLevelDebug=...

Environment Variable:

MOCKSERVER_LAUNCH_UI_FOR_LOG_LEVEL_DEBUG=...

Property File:

mockserver.launchUIForLogLevelDebug=...

Example:

-Dmockserver.launchUIForLogLevelDebug="false"

Enable the recording of metrics for different activities within MockServer, these are exposed via /mockserver/metrics in prometheus format

Type: boolean Default: false

Java Code:

ConfigurationProperties.metricsEnabled(boolean enable)

System Property:

-Dmockserver.metricsEnabled=...

Environment Variable:

MOCKSERVER_METRICS_ENABLED=...

Property File:

mockserver.metricsEnabled=...

Example:

-Dmockserver.metricsEnabled="true"

Register a custom callback that receives every log event generated by MockServer. This is useful for integrating MockServer logging with external systems (e.g. forwarding events to a monitoring tool, custom test reporting, or capturing specific events programmatically during tests).

This feature is programmatic only — there is no system property or environment variable equivalent because the listener is a Java callback.

Java Code:

Configuration.logEventListener(Consumer<LogEntry> listener)
ClientAndServer.setLogEventListener(Consumer<LogEntry> listener)

Example:

ClientAndServer mockServer = ClientAndServer.startClientAndServer(1080);
mockServer.setLogEventListener(logEntry -> {
    System.out.println("Event: " + logEntry.getType() + " - " + logEntry.getTimestamp());
});
 

Memory Usage Configuration:

Maximum number of expectations held in the in-memory ring buffer. Expectations are stored in a circular queue so once this limit is reached the oldest and lowest priority expectations are overwritten.

Type: int Default: minimum of (free heap space in KB / 10) and 15000

The default is calculated automatically based on available JVM heap memory. Each expectation typically uses 4-10 KB of heap for small response bodies. Expectations with large response bodies use significantly more: a 10 KB response body results in ~15-20 KB per expectation, a 50 KB response body results in ~55-75 KB per expectation. With a 256 MB heap, the default is approximately 15,000. You can override this if you need more or want to reduce memory usage.

Power-of-2 sizing: the ring buffer is implemented on top of the LMAX Disruptor, which rounds the configured size up to the next power of 2. Setting maxExpectations=10000 actually allocates 16,384 slots (a 63.8% overhead). To minimise wasted heap, pick a power-of-2 value yourself: 1,024 / 2,048 / 4,096 / 8,192 / 16,384 / 32,768 / 65,536.

Java Code:

ConfigurationProperties.maxExpectations(int count)

System Property:

-Dmockserver.maxExpectations=...

Environment Variable:

MOCKSERVER_MAX_EXPECTATIONS=...

Property File:

mockserver.maxExpectations=...

Example:

-Dmockserver.maxExpectations="2000"

Maximum number of log entries to hold in memory, this includes recorded requests, expectation match failures and other log entries. Log entries are stored in a circular queue so once this limit is reached the oldest entries are overwritten. The lower the log level the more log entries will be captured, particularly at TRACE level logging.

Type: int Default: minimum of (free heap space in KB / 8) and 100000

The default is calculated automatically based on available JVM heap memory. Each log entry typically uses 4-10 KB of heap for small request/response bodies, but log entries for large responses are proportionally larger (e.g., a 100 KB response body produces log entries of ~100+ KB each). Each HTTP request generates 2-3 log entries (request recording, expectation match, and response) that are always stored regardless of log level. With a 256 MB heap the default of approximately 20,000 entries covers around 7,000-10,000 HTTP requests before the oldest entries are evicted. For high-throughput use cases or large response bodies, reduce this value to limit memory usage and GC pressure. See troubleshooting performance for detailed guidance.

Power-of-2 sizing: the log ring buffer is implemented on top of the LMAX Disruptor, which rounds the configured size up to the next power of 2. Setting maxLogEntries=10000 allocates 16,384 slots; setting maxLogEntries=20000 allocates 32,768 slots. To minimise wasted heap, pick a power-of-2 value yourself: 4,096 (~32 MB) / 16,384 (~131 MB) / 65,536 (~524 MB) are good starting points.

Java Code:

ConfigurationProperties.maxLogEntries(int count)

System Property:

-Dmockserver.maxLogEntries=...

Environment Variable:

MOCKSERVER_MAX_LOG_ENTRIES=...

Property File:

mockserver.maxLogEntries=...

Example:

-Dmockserver.maxLogEntries="20000"

Maximum number of remote (not the same JVM) method callbacks (i.e. web sockets) registered for expectations. The web socket client registry entries are stored in a circular queue so once this limit is reach the oldest are overwritten.

Type: int Default: 1500

Java Code:

ConfigurationProperties.maxWebSocketExpectations(int count)

System Property:

-Dmockserver.maxWebSocketExpectations=...

Environment Variable:

MOCKSERVER_MAX_WEB_SOCKET_EXPECTATIONS=...

Property File:

mockserver.maxWebSocketExpectations=...

Example:

-Dmockserver.maxWebSocketExpectations="2000"

Output JVM memory usage metrics to CSV file periodically called memoryUsage_<yyyy-MM-dd>.csv

Type: boolean Default: false

Java Code:

ConfigurationProperties.outputMemoryUsageCsv(boolean enable)

System Property:

-Dmockserver.outputMemoryUsageCsv=...

Environment Variable:

MOCKSERVER_OUTPUT_MEMORY_USAGE_CSV=...

Property File:

mockserver.outputMemoryUsageCsv=...

Example:

-Dmockserver.outputMemoryUsageCsv="true"

Directory to output JVM memory usage metrics CSV files to when outputMemoryUsageCsv enabled

Type: String Default: "."

Java Code:

ConfigurationProperties.memoryUsageCsvDirectory(String directory)

System Property:

-Dmockserver.memoryUsageCsvDirectory=...

Environment Variable:

MOCKSERVER_MEMORY_USAGE_CSV_DIRECTORY=...

Property File:

mockserver.memoryUsageCsvDirectory=...

Example:

-Dmockserver.memoryUsageCsvDirectory="."
   

Memory Tuning Guide

MockServer stores expectations and log entries in memory using ring buffers. The two most important settings that affect memory usage are maxExpectations and maxLogEntries. Each HTTP request processed by MockServer generates 2-3 log entries (the request itself, the expectation match result, and the response).

Both settings have automatic defaults based on available JVM heap space. The table below provides recommended values if you want to override the defaults for different heap sizes:

JVM Heap Size maxExpectations maxLogEntries Approx HTTP Requests Retained
256 MB 1,000 5,000 ~1,500 - 2,500
512 MB 2,000 15,000 ~5,000 - 7,500
1 GB 5,000 40,000 ~13,000 - 20,000

These are conservative estimates assuming typical request/response sizes of 1-5 KB. Large request or response bodies will consume more memory per entry.

Tips for reducing memory usage:

  • Reduce maxLogEntries to limit the number of stored request/response log entries
  • Reduce maxExpectations if expectations contain large response bodies
  • Increase JVM heap size (-Xmx) to give the garbage collector more headroom
  • Use outputMemoryUsageCsv to monitor actual heap usage and tune values accordingly

Docker example with memory-constrained settings:

docker run -d --rm -p 1080:1080 \
  --env MOCKSERVER_MAX_EXPECTATIONS=1000 \
  --env MOCKSERVER_MAX_LOG_ENTRIES=5000 \
  mockserver/mockserver

Introduces a delay (in milliseconds) before protocol detection on new TCP connections. This can be used to simulate slow connection establishment, such as when testing client timeout handling or connection pooling behaviour under latency.

Type: long Default: 0

Java Code:

ConfigurationProperties.connectionDelayMillis(long millis)
Configuration.connectionDelay(Delay delay)

System Property:

-Dmockserver.connectionDelayMillis=...

Environment Variable:

MOCKSERVER_CONNECTION_DELAY_MILLIS=...

Property File:

mockserver.connectionDelayMillis=...

Example:

-Dmockserver.connectionDelayMillis="500"
 

Troubleshooting: MockServer Becomes Slow or Unresponsive

If MockServer appears to freeze, hang, or become progressively slower under sustained load, the most likely cause is memory pressure from log entry accumulation. This section explains why it happens and how to fix it.

Why Does MockServer Slow Down?

Every HTTP request that MockServer processes generates 2-3 log entries that are stored in memory regardless of the configured log level. These entries record the received request, expectation match result, and response — they are always stored to support request verification. Each log entry consumes approximately 4-10 KB of heap for small request/response bodies, scaling proportionally for larger bodies. Under sustained high-throughput load, log entry allocation drives significant GC pressure:

Request Rate Response Body Size Log Data Generated Per Minute
1 req/s 1 KB ~1 MB
10 req/s 1 KB ~12 MB
10 req/s 100 KB ~120 MB
1 req/s 1 MB+ ~120 MB

Log entries are stored in a bounded circular queue (maxLogEntries), so total memory usage does not grow indefinitely. However, the constant allocation and eviction of log entries creates GC pressure. When the JVM heap fills up, the garbage collector runs more frequently and for longer, causing pauses that make MockServer appear to freeze. In extreme cases, the JVM may spend almost all of its time in garbage collection, effectively halting request processing.

Large response bodies amplify this problem significantly. A single expectation returning a 10 MB response at 1 request per second generates over 600 MB of log data per minute — far more than a default heap can handle. Even with ring buffer eviction, the JVM must allocate and then garbage-collect these large objects continuously.

Note: Expectations with large response bodies also consume heap proportionally (e.g., a 50 KB response body results in ~55-75 KB per stored expectation). If you have many expectations with large bodies, reduce maxExpectations as well.

How To Fix It

Apply one or more of the following, depending on your use case:

Fix When To Use Trade-off
Increase JVM heap size Always recommended for large responses or high request rates Uses more container/host memory
Reduce maxLogEntries The single most effective fix — fewer entries means less memory and less GC pressure Fewer requests available for verification
Reduce maxExpectations When expectations contain large response bodies Fewer expectations can be stored simultaneously

Note on logLevel and disableLogging: Setting logLevel to WARN reduces diagnostic TRACE/DEBUG log entries but does not prevent request/response recording — the memory-intensive log entries (received requests, matched expectations, and responses) are always stored regardless of log level, as they are required for verification. Similarly, disableLogging only suppresses system-out output and does not reduce memory usage. To reduce memory, lower maxLogEntries or increase heap size.

Recommended Configurations

High-throughput with small responses (e.g., API mocking at >10 req/s with <10 KB bodies):

docker run -d --rm -p 1080:1080 \
  -e MOCKSERVER_MAX_LOG_ENTRIES=5000 \
  mockserver/mockserver

Large response bodies (e.g., responses >100 KB):

docker run -d --rm -p 1080:1080 \
  -e JAVA_TOOL_OPTIONS="-Xmx1g" \
  -e MOCKSERVER_MAX_LOG_ENTRIES=1000 \
  -e MOCKSERVER_MAX_EXPECTATIONS=100 \
  mockserver/mockserver

Maximum throughput, minimal memory (verification limited to most recent requests):

docker run -d --rm -p 1080:1080 \
  -e JAVA_TOOL_OPTIONS="-Xmx512m" \
  -e MOCKSERVER_MAX_LOG_ENTRIES=100 \
  mockserver/mockserver

Configuring JVM Heap Size

The default JVM heap in the MockServer Docker image is determined by the JVM's container-aware defaults (typically 25% of the container's memory limit). To set an explicit heap size, use the JAVA_TOOL_OPTIONS environment variable:

docker run -d --rm -p 1080:1080 \
  -e JAVA_TOOL_OPTIONS="-Xmx512m" \
  mockserver/mockserver

When running with docker compose:

services:
  mockServer:
    image: mockserver/mockserver
    ports:
      - "1080:1080"
    environment:
      JAVA_TOOL_OPTIONS: "-Xmx512m"
      MOCKSERVER_MAX_LOG_ENTRIES: "5000"

When running as a standalone JAR:

java -Xmx512m -jar mockserver-netty.jar -serverPort 1080

Monitoring Memory Usage

To diagnose memory issues, enable CSV memory tracking:

docker run -d --rm -p 1080:1080 \
  -e MOCKSERVER_OUTPUT_MEMORY_USAGE_CSV=true \
  -e MOCKSERVER_MEMORY_USAGE_CSV_DIRECTORY=/config \
  -v $(pwd):/config \
  mockserver/mockserver

This creates a memoryUsage_<date>.csv file that records heap usage, log entry count, and expectation count over time. If you see heap usage consistently near the maximum, increase -Xmx or reduce maxLogEntries.

Scalability Configuration:

Number of threads for main event loop

These threads are used for fast non-blocking activities such as:

  • reading and de-serialise all requests
  • serialising and writing control plane responses
  • adding, updating or removing expectations
  • verifying requests or request sequences
  • retrieving logs

Expectation actions are handled in a separate thread pool to ensure slow object or class callbacks and response / forward delays do not impact the main event loop.

Type: int Default: 5

Java Code:

ConfigurationProperties.nioEventLoopThreadCount(int count)

System Property:

-Dmockserver.nioEventLoopThreadCount=...

Environment Variable:

MOCKSERVER_NIO_EVENT_LOOP_THREAD_COUNT=...

Property File:

mockserver.nioEventLoopThreadCount=...

Example:

-Dmockserver.nioEventLoopThreadCount="5"

Number of threads for the action handler thread pool

These threads are used for handling actions such as:

  • serialising and writing expectation or proxied responses
  • handling response delays in a non-blocking way (i.e. using a scheduler)
  • executing class callbacks
  • handling method / closure callbacks (using web sockets)

Type: int Default: maximum of 5 or available processors count

Java Code:

ConfigurationProperties.actionHandlerThreadCount(int count)

System Property:

-Dmockserver.actionHandlerThreadCount=...

Environment Variable:

MOCKSERVER_ACTION_HANDLER_THREAD_COUNT=...

Property File:

mockserver.actionHandlerThreadCount=...

Example:

-Dmockserver.actionHandlerThreadCount="5"

Number of threads for client event loop when calling downstream

These threads are used for fast non-blocking activities such as, reading and de-serialise all requests and responses

Type: int Default: 5

Java Code:

ConfigurationProperties.clientNioEventLoopThreadCount(int count)

System Property:

-Dmockserver.clientNioEventLoopThreadCount=...

Environment Variable:

MOCKSERVER_CLIENT_NIO_EVENT_LOOP_THREAD_COUNT=...

Property File:

mockserver.clientNioEventLoopThreadCount=...

Example:

-Dmockserver.clientNioEventLoopThreadCount="5"

Number of threads for each expectation with a method / closure callback (i.e. web socket client) in the org.mockserver.client.MockServerClient

This setting only effects the Java client and how requests each method / closure callbacks it can handle, the default is 5 which should be suitable except in extreme cases.

Type: int Default: 5

Java Code:

ConfigurationProperties.webSocketClientEventLoopThreadCount(int count)

System Property:

-Dmockserver.webSocketClientEventLoopThreadCount=...

Environment Variable:

MOCKSERVER_WEB_SOCKET_CLIENT_EVENT_LOOP_THREAD_COUNT=...

Property File:

mockserver.webSocketClientEventLoopThreadCount=...

Example:

-Dmockserver.webSocketClientEventLoopThreadCount="5"

Maximum time allowed in milliseconds for any future to wait, for example when waiting for a response over a web socket callback.

Type: long Default: 90000

Java Code:

ConfigurationProperties.maxFutureTimeout(long milliseconds)

System Property:

-Dmockserver.maxFutureTimeout=...

Environment Variable:

MOCKSERVER_MAX_FUTURE_TIMEOUT=...

Property File:

mockserver.maxFutureTimeout=...

Example:

-Dmockserver.maxFutureTimeout="90000"

If true (the default) request matchers will fail on the first non-matching field, if false request matchers will compare all fields.

Set to false when debugging matching issues to see all mismatching fields in a single log entry. See Troubleshooting Matching for a step-by-step guide.

Type: boolean Default: true

Java Code:

ConfigurationProperties.matchersFailFast(boolean enable)

System Property:

-Dmockserver.matchersFailFast=...

Environment Variable:

MOCKSERVER_MATCHERS_FAIL_FAST=...

Property File:

mockserver.matchersFailFast=...

Example:

-Dmockserver.matchersFailFast="false"

The the minimum level of logs to record in the event log and to output to system out (if system out log output is not disabled). The lower the log level the more log entries will be captured, particularly at TRACE level logging.

Type: string Default: INFO

Java Code:

ConfigurationProperties.logLevel(String level)

System Property:

-Dmockserver.logLevel=...

Environment Variable:

MOCKSERVER_LOG_LEVEL=...

Property File:

mockserver.logLevel=...

The log level, which can be TRACE, DEBUG, INFO, WARN, ERROR, OFF, FINEST, FINE, INFO, WARNING, SEVERE

Example:

-Dmockserver.logLevel="DEBUG"

Disable logging to the system output

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableSystemOut(boolean disableSystemOut)

System Property:

-Dmockserver.disableSystemOut=...

Environment Variable:

MOCKSERVER_DISABLE_SYSTEM_OUT=...

Property File:

mockserver.disableSystemOut=...

Example:

-Dmockserver.disableSystemOut="true"

Disable logging output to system out. Request/response log entries are still recorded in memory for verification.

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableLogging(boolean disableLogging)

System Property:

-Dmockserver.disableLogging=...

Environment Variable:

MOCKSERVER_DISABLE_LOGGING=...

Property File:

mockserver.disableLogging=...

Example:

-Dmockserver.disableLogging="true"

Maximum request body size in bytes that conversation-aware LLM matchers will parse. LLM conversation matchers (whenLatestMessageContains, whenContainsToolResultFor, etc.) parse the inbound request body as JSON to extract the message history. For deep conversation histories or large tool results, this parse step is proportional to body size.

Requests whose body exceeds this cap skip conversation-aware matching and are treated as a no-match for conversation predicates (the scenario state machine is unaffected). Increase this value only when your LLM conversations regularly include very large tool results or long message histories. Reduce it in memory-constrained environments to bound the maximum allocation per matching attempt.

Type: int Default: 1048576 (1 MiB) Range: 16384 (16 KiB) — 67108864 (64 MiB)

Java Code:

ConfigurationProperties.maxLlmConversationBodySize(int size)
Configuration.maxLlmConversationBodySize(Integer size)

System Property:

-Dmockserver.maxLlmConversationBodySize=...

Environment Variable:

MOCKSERVER_MAX_LLM_CONVERSATION_BODY_SIZE=...

Property File:

mockserver.maxLlmConversationBodySize=...

Example:

-Dmockserver.maxLlmConversationBodySize="4194304"
 

Socket Configuration:

Maximum time in milliseconds allowed for a response from a socket

Type: long Default: 20000

Java Code:

ConfigurationProperties.maxSocketTimeout(long milliseconds)

System Property:

-Dmockserver.maxSocketTimeout=...

Environment Variable:

MOCKSERVER_MAX_SOCKET_TIMEOUT=...

Property File:

mockserver.maxSocketTimeout=...

Example:

-Dmockserver.maxSocketTimeout="10000"

Maximum time in milliseconds allowed to connect to a socket

Type: long Default: 20000

Java Code:

ConfigurationProperties.socketConnectionTimeout(long milliseconds)

System Property:

-Dmockserver.socketConnectionTimeout=...

Environment Variable:

MOCKSERVER_SOCKET_CONNECTION_TIMEOUT=...

Property File:

mockserver.socketConnectionTimeout=...

Example:

-Dmockserver.socketConnectionTimeout="10000"

If true socket connections will always be closed after a response is returned, if false connection is only closed if request header indicate connection should be closed.

Type: boolean Default: false

Java Code:

ConfigurationProperties.alwaysCloseSocketConnections(boolean alwaysClose)

System Property:

-Dmockserver.alwaysCloseSocketConnections=...

Environment Variable:

MOCKSERVER_ALWAYS_CLOSE_SOCKET_CONNECTIONS=...

Property File:

mockserver.alwaysCloseSocketConnections=...

Example:

-Dmockserver.alwaysCloseSocketConnections="true"

The local IP address to bind to for accepting new socket connections

Type: string Default: 0.0.0.0

Java Code:

ConfigurationProperties.localBoundIP(String localBoundIP)

System Property:

-Dmockserver.localBoundIP=...

Environment Variable:

MOCKSERVER_LOCAL_BOUND_IP=...

Property File:

mockserver.localBoundIP=...

Example:

-Dmockserver.localBoundIP="0.0.0.0"
 

Http Request Parsing Configuration:

Maximum size the first line of an HTTP request

Type: int Default: Integer.MAX_VALUE

Java Code:

ConfigurationProperties.maxInitialLineLength(int length)

System Property:

-Dmockserver.maxInitialLineLength=...

Environment Variable:

MOCKSERVER_MAX_INITIAL_LINE_LENGTH=...

Property File:

mockserver.maxInitialLineLength=...

Example:

-Dmockserver.maxInitialLineLength="8192"

Maximum size HTTP request headers

Type: int Default: Integer.MAX_VALUE

Java Code:

ConfigurationProperties.maxHeaderSize(int size)

System Property:

-Dmockserver.maxHeaderSize=...

Environment Variable:

MOCKSERVER_MAX_HEADER_SIZE=...

Property File:

mockserver.maxHeaderSize=...

Example:

-Dmockserver.maxHeaderSize="16384"

Maximum size of HTTP chunks in request or responses

Type: int Default: Integer.MAX_VALUE

Java Code:

ConfigurationProperties.maxChunkSize(int size)

System Property:

-Dmockserver.maxChunkSize=...

Environment Variable:

MOCKSERVER_MAX_CHUNK_SIZE=...

Property File:

mockserver.maxChunkSize=...

Example:

-Dmockserver.maxChunkSize="16384"

Maximum aggregated body size (in bytes) accepted on inbound HTTP/1.1 and HTTP/2 requests. Requests larger than this are rejected — HTTP/1.1 clients typically receive a 413 Payload Too Large response, while HTTP/2 streams are reset. Bounding the inbound body protects MockServer from memory exhaustion when a misbehaving or malicious client uploads an extremely large payload.

Type: int Default: 10485760 (10 MiB)

Raise this only if you intentionally mock large uploads. Very large limits make MockServer susceptible to OOM when many concurrent uploads arrive.

Java Code:

ConfigurationProperties.maxRequestBodySize(int size)

System Property:

-Dmockserver.maxRequestBodySize=...

Environment Variable:

MOCKSERVER_MAX_REQUEST_BODY_SIZE=...

Property File:

mockserver.maxRequestBodySize=...

Example:

-Dmockserver.maxRequestBodySize="52428800"

Maximum aggregated body size (in bytes) accepted on responses received from upstream servers when MockServer is acting as a proxy or forwarder.

Type: int Default: 52428800 (50 MiB)

Java Code:

ConfigurationProperties.maxResponseBodySize(int size)

System Property:

-Dmockserver.maxResponseBodySize=...

Environment Variable:

MOCKSERVER_MAX_RESPONSE_BODY_SIZE=...

Property File:

mockserver.maxResponseBodySize=...

Example:

-Dmockserver.maxResponseBodySize="104857600"

Maximum time (in milliseconds) allowed for evaluating a single regular expression during request matching. A pathological pattern (e.g. (a+)+b) that exceeds this budget is treated as a non-match and a WARN log entry is written, so the server cannot be wedged by exponential regex backtracking from a malicious expectation or input. Set to 0 or a negative value to disable the timeout.

Type: long Default: 5000

Java Code:

ConfigurationProperties.regexMatchingTimeoutMillis(long milliseconds)

System Property:

-Dmockserver.regexMatchingTimeoutMillis=...

Environment Variable:

MOCKSERVER_REGEX_MATCHING_TIMEOUT_MILLIS=...

Property File:

mockserver.regexMatchingTimeoutMillis=...

Example:

-Dmockserver.regexMatchingTimeoutMillis="2000"

Maximum time (in milliseconds) allowed for evaluating a single XPath expression against an XML document during request matching. Exceeding this budget is treated as a non-match and a WARN log entry is written, protecting MockServer from XPath-based denial-of-service. Set to 0 or a negative value to disable the timeout.

Type: long Default: 5000

Java Code:

ConfigurationProperties.xpathMatchingTimeoutMillis(long milliseconds)

System Property:

-Dmockserver.xpathMatchingTimeoutMillis=...

Environment Variable:

MOCKSERVER_XPATH_MATCHING_TIMEOUT_MILLIS=...

Property File:

mockserver.xpathMatchingTimeoutMillis=...

Example:

-Dmockserver.xpathMatchingTimeoutMillis="2000"

Fully qualified name of a class that registers custom json-unit matchers, so JSON body expectations can validate dynamic values (e.g. "price must be greater than 100") with the ${json-unit.matches:name} placeholder.

The class must have a public no-arg constructor and implement org.mockserver.matchers.CustomJsonUnitMatcherProvider, returning a Map<String, org.hamcrest.Matcher<?>> keyed by the placeholder name. If the class cannot be loaded, does not implement the interface, or its constructor throws, MockServer logs a WARN and JSON matching falls back to its built-in behaviour.

Type: string Default: "" (no custom matchers)

Example provider:

public class MyJsonUnitMatchers implements CustomJsonUnitMatcherProvider {
    public Map<String, Matcher<?>> jsonUnitMatchers() {
        Map<String, Matcher<?>> matchers = new HashMap<>();
        matchers.put("largerThan", new BaseMatcher<Object>() {
            public boolean matches(Object actual) {
                return new BigDecimal(actual.toString()).compareTo(BigDecimal.valueOf(100)) > 0;
            }
            public void describeTo(Description d) { d.appendText("a number larger than 100"); }
        });
        return matchers;
    }
}

Then reference the matcher from the JSON body of an expectation:

{ "price": "${json-unit.matches:largerThan}" }

Java Code:

ConfigurationProperties.customJsonUnitMatchersClass(String className)

System Property:

-Dmockserver.customJsonUnitMatchersClass=...

Environment Variable:

MOCKSERVER_CUSTOM_JSON_UNIT_MATCHERS_CLASS=...

Property File:

mockserver.customJsonUnitMatchersClass=...

Example:

-Dmockserver.customJsonUnitMatchersClass="com.example.MyJsonUnitMatchers"

When enabled, MockServer rejects forward and proxy targets that resolve to loopback, link-local, RFC 1918 private, or cloud metadata addresses (such as 169.254.169.254). This blocks server-side request forgery (SSRF) attacks where a malicious expectation would otherwise forward through MockServer to internal infrastructure.

Type: boolean Default: false

The default is false because MockServer is most commonly used to mock services running on localhost, Docker bridge networks, or Kubernetes service IPs — blocking those by default would break the common case. Enable this in hardened or multi-tenant deployments where untrusted callers can register expectations.

Java Code:

ConfigurationProperties.forwardProxyBlockPrivateNetworks(boolean block)

System Property:

-Dmockserver.forwardProxyBlockPrivateNetworks=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_BLOCK_PRIVATE_NETWORKS=...

Property File:

mockserver.forwardProxyBlockPrivateNetworks=...

Example:

-Dmockserver.forwardProxyBlockPrivateNetworks="true"

Whether to honour TLSv1 and TLSv1.1 in tlsProtocols. Both protocols are deprecated by RFC 8996 and vulnerable to BEAST and POODLE.

Type: boolean Default: true

The default is true for backwards compatibility — MockServer's tlsProtocols default still includes TLSv1 and TLSv1.1. Set this to false to opt into a hardened profile: any TLSv1 or TLSv1.1 entries in tlsProtocols are filtered out before the SSL context is built. A future major release is expected to flip this default to false.

Java Code:

ConfigurationProperties.tlsAllowInsecureProtocols(boolean allow)

System Property:

-Dmockserver.tlsAllowInsecureProtocols=...

Environment Variable:

MOCKSERVER_TLS_ALLOW_INSECURE_PROTOCOLS=...

Property File:

mockserver.tlsAllowInsecureProtocols=...

Example:

-Dmockserver.tlsAllowInsecureProtocols="false"

If true semicolons are treated as a separator for a query parameter string, if false the semicolon is treated as a normal character that is part of a query parameter value.

Type: boolean Default: true

Java Code:

ConfigurationProperties.useSemicolonAsQueryParameterSeparator(boolean useSemicolonAsQueryParameterSeparator)

System Property:

-Dmockserver.useSemicolonAsQueryParameterSeparator=...

Environment Variable:

MOCKSERVER_USE_SEMICOLON_AS_QUERY_PARAMETER_SEPARATOR=...

Property File:

mockserver.useSemicolonAsQueryParameterSeparator=...

Example:

-Dmockserver.useSemicolonAsQueryParameterSeparator="false"

If false requests are assumed as binary if the method isn't one of "GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE", "TRACE" or "CONNECT"

Type: boolean Default: false

Java Code:

ConfigurationProperties.assumeAllRequestsAreHttp(boolean assumeAllRequestsAreHttp)

System Property:

-Dmockserver.assumeAllRequestsAreHttp=...

Environment Variable:

MOCKSERVER_ASSUME_ALL_REQUESTS_ARE_HTTP=...

Property File:

mockserver.assumeAllRequestsAreHttp=...

Example:

-Dmockserver.assumeAllRequestsAreHttp="true"

If false HTTP/2 is disabled so MockServer no longer advertises h2 during TLS ALPN negotiation (and does not detect the HTTP/2 cleartext h2c upgrade). HTTP/2 capable clients then fall back to HTTP/1.1, which is useful for testing how a client behaves over HTTP/1.1 without changing the client itself.

Type: boolean Default: true

Java Code:

ConfigurationProperties.http2Enabled(boolean http2Enabled)

System Property:

-Dmockserver.http2Enabled=...

Environment Variable:

MOCKSERVER_HTTP2_ENABLED=...

Property File:

mockserver.http2Enabled=...

Example:

-Dmockserver.http2Enabled="false"
 

CORS Configuration:

Enable CORS for MockServer REST API so that the API can be used for javascript running in browsers, such as selenium

Type: boolean Default: false

Java Code:

ConfigurationProperties.enableCORSForAPI(boolean enableCORSForAPI)

System Property:

-Dmockserver.enableCORSForAPI=...

Environment Variable:

MOCKSERVER_ENABLE_CORS_FOR_API=...

Property File:

mockserver.enableCORSForAPI=...

Example:

-Dmockserver.enableCORSForAPI="true"

Enable CORS for all responses from MockServer, including the REST API and expectation responses

Type: boolean Default: false

Java Code:

ConfigurationProperties.enableCORSForAllResponses(boolean enableCORSForAllResponses)

System Property:

-Dmockserver.enableCORSForAllResponses=...

Environment Variable:

MOCKSERVER_ENABLE_CORS_FOR_ALL_RESPONSES=...

Property File:

mockserver.enableCORSForAllResponses=...

Example:

-Dmockserver.enableCORSForAllResponses="true"

The value used for CORS in the access-control-allow-origin header.

Note: To ensure access-control-allow-credentials works correctly, when corsAllowCredentials is true the CORS header access-control-allow-origin will set its value using the origin header on requests instead of corsAllowOrigin property.

Type: string Default: ""

Java Code:

ConfigurationProperties.corsAllowOrigin(String corsAllowOrigin)

System Property:

-Dmockserver.corsAllowOrigin=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_ORIGIN=...

Property File:

mockserver.corsAllowOrigin=...

Example:

-Dmockserver.corsAllowOrigin="*"

The value used for CORS in the access-control-allow-methods header.

Type: string Default: ""

Java Code:

ConfigurationProperties.corsAllowMethods(String corsAllowMethods)

System Property:

-Dmockserver.corsAllowMethods=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_METHODS=...

Property File:

mockserver.corsAllowMethods=...

Example:

-Dmockserver.corsAllowMethods="CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE"

Default value used for CORS in the access-control-allow-headers and access-control-expose-headers headers.

In addition to this default value any headers specified in the request header access-control-request-headers also get added to access-control-allow-headers and access-control-expose-headers headers in a CORS response.

Type: string Default: ""

Java Code:

ConfigurationProperties.corsAllowHeaders(String corsAllowHeaders)

System Property:

-Dmockserver.corsAllowHeaders=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_HEADERS=...

Property File:

mockserver.corsAllowHeaders=...

Example:

-Dmockserver.corsAllowHeaders="Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization"

The value used for CORS in the access-control-allow-credentials header.

Note: To ensure access-control-allow-credentials works correctly, when corsAllowCredentials is true the CORS header access-control-allow-origin will set its value using the origin header on requests instead of corsAllowOrigin property.

Type: boolean Default: false

Java Code:

ConfigurationProperties.corsAllowCredentials(boolean allow)

System Property:

-Dmockserver.corsAllowCredentials=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_CREDENTIALS=...

Property File:

mockserver.corsAllowCredentials=...

Example:

-Dmockserver.corsAllowCredentials="true"

The value used for CORS in the access-control-max-age header.

Type: int Default: 0

Java Code:

ConfigurationProperties.corsMaxAgeInSeconds(int maxAgeInSeconds)

System Property:

-Dmockserver.corsMaxAgeInSeconds=...

Environment Variable:

MOCKSERVER_CORS_MAX_AGE_IN_SECONDS=...

Property File:

mockserver.corsMaxAgeInSeconds=...

Example:

-Dmockserver.corsMaxAgeInSeconds=300
 

Template Restriction Configuration:

Set comma separate list of classes not allowed to be used by javascript templates

Type: string Default: ""

Java Code:

ConfigurationProperties.javascriptDisallowedClasses(String javascriptDisallowedClasses)

System Property:

-Dmockserver.javascriptDisallowedClasses=...

Environment Variable:

MOCKSERVER_JAVASCRIPT_DISALLOWED_CLASSES=...

Property File:

mockserver.javascriptDisallowedClasses=...

Example:

-Dmockserver.javascriptDisallowedClasses="java.lang.Runtime,java.lang.Class"

Set comma separate list of text not allowed to be contained in javascript templates

Type: string Default: ""

Java Code:

ConfigurationProperties.javascriptDisallowedText(String javascriptDisallowedText)

System Property:

-Dmockserver.javascriptDisallowedText=...

Environment Variable:

MOCKSERVER_JAVASCRIPT_DISALLOWED_TEXT=...

Property File:

mockserver.javascriptDisallowedText=...

Example:

-Dmockserver.javascriptDisallowedText="getRuntime().exec"

If true class loading is not allowed in velocity templates

Type: boolean Default: false

Java Code:

ConfigurationProperties.velocityDisallowClassLoading(boolean velocityDisallowClassLoading)

System Property:

-Dmockserver.velocityDisallowClassLoading=...

Environment Variable:

MOCKSERVER_VELOCITY_DISALLOW_CLASS_LOADING=...

Property File:

mockserver.velocityDisallowClassLoading=...

Example:

-Dmockserver.velocityDisallowClassLoading="true"

Set comma separate list of text not allowed to be contained in velocity templates

Type: string Default: ""

Java Code:

ConfigurationProperties.velocityDisallowedText(String velocityDisallowedText)

System Property:

-Dmockserver.velocityDisallowedText=...

Environment Variable:

MOCKSERVER_VELOCITY_DISALLOWED_TEXT=...

Property File:

mockserver.velocityDisallowedText=...

Example:

-Dmockserver.velocityDisallowedText="request.class"

Set comma separate list of text not allowed to be contained in mustache templates

Type: string Default: ""

Java Code:

ConfigurationProperties.mustacheDisallowedText(String mustacheDisallowedText)

System Property:

-Dmockserver.mustacheDisallowedText=...

Environment Variable:

MOCKSERVER_MUSTACHE_DISALLOWED_TEXT=...

Property File:

mockserver.mustacheDisallowedText=...

Example:

-Dmockserver.mustacheDisallowedText="request.method"
 

Initialization & Persistence Configuration:

The class (and package) used to initialize expectations in MockServer at startup, if set MockServer will load and call this class to initialise expectations when is starts.

Type: string Default: null

Java Code:

ConfigurationProperties.initializationClass(String initializationClass)

System Property:

-Dmockserver.initializationClass=...

Environment Variable:

MOCKSERVER_INITIALIZATION_CLASS=...

Property File:

mockserver.initializationClass=...

Spring @MockServerTest:

@MockServerTest("mockserver.initializationClass=org.mockserver.server.initialize.ExpectationInitializerExample")

Example:

-Dmockserver.initializationClass="org.mockserver.server.initialize.ExpectationInitializerExample"

The path to the json file used to initialize expectations in MockServer at startup, if set MockServer will load this file and initialise expectations for each item in the file when is starts.

The expected format of the file is a JSON array of expectations, as per the REST API format

Type: string Default: null

Java Code:

ConfigurationProperties.initializationJsonPath(String initializationJsonPath)

System Property:

-Dmockserver.initializationJsonPath=...

Environment Variable:

MOCKSERVER_INITIALIZATION_JSON_PATH=...

Property File:

mockserver.initializationJsonPath=...

Example:

-Dmockserver.initializationJsonPath="org/mockserver/server/initialize/initializerJson.json"

The path to the OpenAPI spec file used to initialize expectations in MockServer at startup, if set MockServer will load this file and create expectations for each operation when it starts.

The file can be a YAML (.yaml, .yml) or JSON (.json) OpenAPI v3 specification. MockServer will generate an expectation for each operation defined in the spec, with example responses derived from the schema.

To watch multiple files use file globs as documented here: glob patterns

Type: string Default: null

Java Code:

ConfigurationProperties.initializationOpenAPIPath(String initializationOpenAPIPath)

System Property:

-Dmockserver.initializationOpenAPIPath=...

Environment Variable:

MOCKSERVER_INITIALIZATION_OPENAPI_PATH=...

Property File:

mockserver.initializationOpenAPIPath=...

Example:

-Dmockserver.initializationOpenAPIPath="/config/petstore.yaml"

If enabled the initialization JSON file and OpenAPI file will be watched for changes, any changes found will result in expectations being created, removed or updated by matching against their key.

If duplicate keys exist only the last duplicate key in the file will be processed and all duplicates except the last duplicate will be removed.

The order of expectations in the file is the order in which they are created if they are new, however, re-ordering existing expectations does not change the order they are matched against incoming requests.

Type: boolean Default: false

Java Code:

ConfigurationProperties.watchInitializationJson(boolean enable)

System Property:

-Dmockserver.watchInitializationJson=...

Environment Variable:

MOCKSERVER_WATCH_INITIALIZATION_JSON=...

Property File:

mockserver.watchInitializationJson=...

Example:

-Dmockserver.watchInitializationJson="false"

Enable the persisting of expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistExpectations(boolean persistExpectations)

System Property:

-Dmockserver.persistExpectations=...

Environment Variable:

MOCKSERVER_PERSIST_EXPECTATIONS=...

Property File:

mockserver.persistExpectations=...

Example:

-Dmockserver.persistExpectations="true"

The file path used to save persisted expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)

Type: string Default: persistedExpectations.json

Java Code:

ConfigurationProperties.persistedExpectationsPath(String persistedExpectationsPath)

System Property:

-Dmockserver.persistedExpectationsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_EXPECTATIONS_PATH=...

Property File:

mockserver.persistedExpectationsPath=...

Example:

-Dmockserver.persistedExpectationsPath="org/mockserver/server/initialize/initializerJson.json"

Enable the persisting of recorded expectations (proxy traffic) as json, which is updated whenever a new request is forwarded through the proxy.

The persisted file can be loaded on restart using initializationJsonPath to replay recorded traffic as mock expectations.

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistRecordedExpectations(boolean enable)

System Property:

-Dmockserver.persistRecordedExpectations=...

Environment Variable:

MOCKSERVER_PERSIST_RECORDED_EXPECTATIONS=...

Property File:

mockserver.persistRecordedExpectations=...

Example:

-Dmockserver.persistRecordedExpectations="true"

The file path used to save persisted recorded expectations as json, which is updated whenever a new request is forwarded through the proxy.

Type: string Default: persistedRecordedExpectations.json

Java Code:

ConfigurationProperties.persistedRecordedExpectationsPath(String persistedRecordedExpectationsPath)

System Property:

-Dmockserver.persistedRecordedExpectationsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_RECORDED_EXPECTATIONS_PATH=...

Property File:

mockserver.persistedRecordedExpectationsPath=...

Example:

-Dmockserver.persistedRecordedExpectationsPath="recordedExpectations.json"
 

Verification Configuration:

The maximum number of requests to return in verification failure result, if more expectations are found the failure result does not list them separately

Type: int Default: 10

Java Code:

ConfigurationProperties.maximumNumberOfRequestToReturnInVerificationFailure(Integer maximumNumberOfRequestToReturnInVerificationFailure)

System Property:

-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure=...

Environment Variable:

MOCKSERVER_MAXIMUM_NUMBER_OF_REQUESTS_TO_RETURN_IN_VERIFICATION_FAILURE=...

Property File:

mockserver.maximumNumberOfRequestToReturnInVerificationFailure=...

Example:

-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure="20"
 

Proxying Configuration:

Note: HTTP/2 proxying has limitations. When MockServer forwards requests to downstream services, HTTP/2 requests are downgraded to HTTP/1.1. MockServer can accept HTTP/2 connections and serve mock responses over HTTP/2, but forwarded/proxied requests are always sent as HTTP/1.1. See HTTP/2 proxy limitations for details.

If true (the default) when no matching expectation is found, and the host header of the request does not match MockServer's host, then MockServer attempts to proxy the request. If the upstream server is unreachable (connection refused, TLS error, timeout, etc.) a 502 Bad Gateway is returned. If no matching expectation is found and the request is not eligible for proxying, a 404 is returned.

If false when no matching expectation is found, and MockServer is not being used as a proxy, then MockServer always returns a 404 immediately.

Note: this property only triggers proxy behaviour when the Host header in the request differs from MockServer's own local addresses (e.g., localhost, 127.0.0.1, or the machine's hostname). If the Host header matches MockServer's address, the request is not forwarded regardless of this setting. In Docker, set this via environment variable: MOCKSERVER_ATTEMPT_TO_PROXY_IF_NO_MATCHING_EXPECTATION=true.

Type: boolean Default: true

Java Code:

ConfigurationProperties.attemptToProxyIfNoMatchingExpectation(boolean enable)

System Property:

-Dmockserver.attemptToProxyIfNoMatchingExpectation=...

Environment Variable:

MOCKSERVER_ATTEMPT_TO_PROXY_IF_NO_MATCHING_EXPECTATION=...

Property File:

mockserver.attemptToProxyIfNoMatchingExpectation=...

Example:

-Dmockserver.attemptToProxyIfNoMatchingExpectation="false"

Use HTTP proxy (i.e. via Host header) for all outbound / forwarded requests

Type: string Default: null

Java Code:

ConfigurationProperties.forwardHttpProxy(String hostAndPort)

System Property:

-Dmockserver.forwardHttpProxy=...

Environment Variable:

MOCKSERVER_FORWARD_HTTP_PROXY=...

Property File:

mockserver.forwardHttpProxy=...

Example:

-Dmockserver.forwardHttpProxy="127.0.0.1:1090"

Use HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests, supports TLS tunnelling of HTTPS requests

Type: string Default: null

Java Code:

ConfigurationProperties.forwardHttpsProxy(String hostAndPort)

System Property:

-Dmockserver.forwardHttpsProxy=...

Environment Variable:

MOCKSERVER_FORWARD_HTTPS_PROXY=...

Property File:

mockserver.forwardHttpsProxy=...

Example:

-Dmockserver.forwardHttpsProxy="127.0.0.1:1090"

Use SOCKS proxy for all outbound / forwarded requests, support TLS tunnelling of TCP connections

Type: string Default: null

Java Code:

ConfigurationProperties.forwardSocksProxy(String hostAndPort)

System Property:

-Dmockserver.forwardSocksProxy=...

Environment Variable:

MOCKSERVER_FORWARD_SOCKS_PROXY=...

Property File:

mockserver.forwardSocksProxy=...

Example:

-Dmockserver.forwardSocksProxy="127.0.0.1:1090"

Username for proxy authentication when using HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests

Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername)

System Property:

-Dmockserver.forwardProxyAuthenticationUsername=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_AUTHENTICATION_USERNAME=...

Property File:

mockserver.forwardProxyAuthenticationUsername=...

Example:

-Dmockserver.forwardProxyAuthenticationUsername=john.doe

Password for proxy authentication when using HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests

Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword)

System Property:

-Dmockserver.forwardProxyAuthenticationPassword=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_AUTHENTICATION_PASSWORD=...

Property File:

mockserver.forwardProxyAuthenticationPassword=...

Example:

-Dmockserver.forwardProxyAuthenticationPassword="p@ssw0rd"

The authentication realm for proxy authentication to MockServer

Type: string Default: MockServer HTTP Proxy

Java Code:

ConfigurationProperties.proxyAuthenticationRealm(String proxyAuthenticationRealm)

System Property:

-Dmockserver.proxyAuthenticationRealm=...

Environment Variable:

MOCKSERVER_PROXY_SERVER_REALM=...

Property File:

mockserver.proxyAuthenticationRealm=...

Example:

-Dmockserver.proxyAuthenticationRealm="MockServer HTTP Proxy"

The required username for proxy authentication to MockServer

Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.

Type: string Default:

Java Code:

ConfigurationProperties.proxyAuthenticationUsername(String proxyAuthenticationUsername)

System Property:

-Dmockserver.proxyAuthenticationUsername=...

Environment Variable:

MOCKSERVER_PROXY_AUTHENTICATION_USERNAME=...

Property File:

mockserver.proxyAuthenticationUsername=...

Example:

-Dmockserver.proxyAuthenticationUsername=john.doe

The required password for proxy authentication to MockServer

Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.

Type: string Default:

Java Code:

ConfigurationProperties.proxyAuthenticationPassword(String proxyAuthenticationPassword)

System Property:

-Dmockserver.proxyAuthenticationPassword=...

Environment Variable:

MOCKSERVER_PROXY_AUTHENTICATION_PASSWORD=...

Property File:

mockserver.proxyAuthenticationPassword=...

Example:

-Dmockserver.proxyAuthenticationPassword="p@ssw0rd"

Configure reverse proxy mappings that route incoming requests by path prefix to upstream servers with automatic path rewriting. This provides Apache-style ProxyPass functionality.

Value is a JSON array of objects. Each object has:

  • pathPrefix (required) — the incoming path prefix to match, e.g. /api/
  • targetUri (required) — the upstream server URI including path, e.g. https://backend:8443/services/
  • preserveHost (optional, default false) — if true, the original Host header is preserved instead of being adjusted to match the target

Path rewriting example: with pathPrefix="/api/" and targetUri="https://backend:8443/services/", a request to GET /api/users/123 is forwarded as GET /services/users/123 to backend:8443 over HTTPS.

Mappings are evaluated in order; the first matching prefix wins. ProxyPass is evaluated after expectations and CORS, but before the speculative proxy attempt.

Type: JSON array Default: []

Java Code:

ConfigurationProperties.proxyPass("[{\"pathPrefix\":\"/api/\",\"targetUri\":\"https://backend:8443/services/\"}]")

System Property:

-Dmockserver.proxyPass=...

Environment Variable:

MOCKSERVER_PROXY_PASS=...

Property File:

mockserver.proxyPass=[{"pathPrefix":"/api/","targetUri":"https://backend:8443/services/"}]

Example:

MOCKSERVER_PROXY_PASS='[{"pathPrefix":"/api/","targetUri":"https://backend:8443/services/"},{"pathPrefix":"/auth/","targetUri":"http://auth-server:9090/","preserveHost":true}]'

Comma-separated list of hostnames that MockServer should not proxy to. When a request's Host header matches one of these hosts, MockServer will return a 404 instead of forwarding the request. This applies both to direct proxying and to upstream proxy bypass.

Supports exact hostnames (e.g. example.com), wildcard prefixes (e.g. *.internal.corp), and IP addresses (e.g. 192.168.1.1).

Type: string Default: ""

Java Code:

ConfigurationProperties.noProxyHosts(String noProxyHosts)

System Property:

-Dmockserver.noProxyHosts=...

Environment Variable:

MOCKSERVER_NO_PROXY_HOSTS=...

Property File:

mockserver.noProxyHosts=...

Example:

-Dmockserver.noProxyHosts="*.internal.corp,localhost,192.168.1.1"

If true (the default) the Host header will be automatically adjusted to match the target server when forwarding requests via HttpOverrideForwardedRequest or template-based forwards. This prevents HTTP 421 Misdirected Request errors when the target server validates Host headers.

If false the original Host header is preserved unless explicitly overridden in the request override.

Note: When an explicit Host header is provided in the request override, it is always preserved regardless of this setting. Similarly, when a template explicitly sets the Host header to a value different from the original request, it is preserved. Header changes made via requestModifier are still subject to auto-adjustment. This setting only applies when the Host header is not explicitly overridden and a socketAddress is specified for routing.

Type: boolean Default: true

Java Code:

ConfigurationProperties.forwardAdjustHostHeader(boolean enable)

System Property:

-Dmockserver.forwardAdjustHostHeader=...

Environment Variable:

MOCKSERVER_FORWARD_ADJUST_HOST_HEADER=...

Property File:

mockserver.forwardAdjustHostHeader=...

Example:

-Dmockserver.forwardAdjustHostHeader="false"

Set a default Host header value to use when forwarding requests. When set, the Host header will be overridden with this value for all forwarded requests, regardless of the target server's address. This is useful when the target proxy server routes requests based on the Host header.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardDefaultHostHeader(String hostHeader)

System Property:

-Dmockserver.forwardDefaultHostHeader=...

Environment Variable:

MOCKSERVER_FORWARD_DEFAULT_HOST_HEADER=...

Property File:

mockserver.forwardDefaultHostHeader=...

Example:

-Dmockserver.forwardDefaultHostHeader="foo.com"

The hostname of the remote server to forward all unmatched requests to. When set together with proxyRemotePort, MockServer acts as a forward proxy, sending any request that does not match an expectation to the specified remote host. The Host header is automatically updated to match the configured remote host unless forwardDefaultHostHeader is set. This works in all deployment modes including WAR deployments.

Type: string Default: "" (unset)

Java Code:

ConfigurationProperties.proxyRemoteHost(String hostname)

System Property:

-Dmockserver.proxyRemoteHost=...

Environment Variable:

MOCKSERVER_PROXY_REMOTE_HOST=...

Property File:

mockserver.proxyRemoteHost=...

Example:

-Dmockserver.proxyRemoteHost="www.mock-server.com"

The port of the remote server to forward all unmatched requests to. Must be specified together with proxyRemoteHost. Valid values are 1-65535.

Type: integer Default: null

Java Code:

ConfigurationProperties.proxyRemotePort(Integer port)

System Property:

-Dmockserver.proxyRemotePort=...

Environment Variable:

MOCKSERVER_PROXY_REMOTE_PORT=...

Property File:

mockserver.proxyRemotePort=...

Example:

-Dmockserver.proxyRemotePort="443"
 

Streaming Proxy Configuration:

These properties control how MockServer handles streaming responses (Server-Sent Events with Content-Type: text/event-stream) when acting as a proxy. This is particularly relevant when proxying LLM API traffic from AI coding agents. See Inspect AI Agent Traffic for a full usage guide.

If true (the default) streaming responses (Server-Sent Events with Content-Type: text/event-stream) received while proxying are relayed to the client incrementally as they arrive, instead of being fully buffered before being forwarded. This keeps streaming APIs such as LLM APIs (Anthropic, OpenAI) responsive when proxied. Streaming is auto-detected from the Content-Type response header and does not affect non-streaming responses. Ordinary chunked responses (without text/event-stream) are always aggregated normally.

Set to false to revert to the previous behaviour of fully buffering every proxied response before forwarding it.

Type: boolean Default: true

Java Code:

ConfigurationProperties.streamingResponsesEnabled(boolean enable)

System Property:

-Dmockserver.streamingResponsesEnabled=...

Environment Variable:

MOCKSERVER_STREAMING_RESPONSES_ENABLED=...

Property File:

mockserver.streamingResponsesEnabled=...

Example:

-Dmockserver.streamingResponsesEnabled="false"

The maximum number of bytes of a streaming response body captured into the event log while relaying it. The full stream is always relayed to the client; this only bounds how much is retained for the dashboard Traffic Inspector and the retrieve API. Once this limit is exceeded, the logged body is truncated and the response is flagged with x-mockserver-stream-truncated: true. Increase this value if you need to capture full LLM completions longer than 256 KB.

Type: int Default: 262144 (256 KB)

Java Code:

ConfigurationProperties.maxStreamingCaptureBytes(int bytes)

System Property:

-Dmockserver.maxStreamingCaptureBytes=...

Environment Variable:

MOCKSERVER_MAX_STREAMING_CAPTURE_BYTES=...

Property File:

mockserver.maxStreamingCaptureBytes=...

Example:

-Dmockserver.maxStreamingCaptureBytes="524288"

The maximum inbound request body size (in bytes) that LLM conversation-aware matchers will parse when evaluating predicates such as whenLatestMessageContains or whenContainsToolResultFor. Requests larger than this value skip conversation-aware parsing entirely and are treated as no-match by those predicates, which protects the matcher from crafted JSON inputs designed to consume CPU or memory. Values outside the supported range are clamped at startup.

Type: int Default: 1048576 (1 MiB) Range: [16384, 67108864] (16 KiB – 64 MiB)

Java Code:

ConfigurationProperties.maxLlmConversationBodySize(int bytes)

System Property:

-Dmockserver.maxLlmConversationBodySize=...

Environment Variable:

MOCKSERVER_MAX_LLM_CONVERSATION_BODY_SIZE=...

Property File:

mockserver.maxLlmConversationBodySize=...

Example:

-Dmockserver.maxLlmConversationBodySize="2097152"

The maximum time in seconds a streaming response connection may be idle (no chunk received from the upstream server) before MockServer closes it and logs the captured portion as truncated. This replaces the fixed global socket timeout for streaming responses, which would otherwise terminate long-lived LLM completions. The timeout resets on every chunk received, so a slow-but-active stream is never cut off prematurely.

Type: int Default: 60 (seconds)

Java Code:

ConfigurationProperties.streamIdleTimeoutSeconds(int seconds)

System Property:

-Dmockserver.streamIdleTimeoutSeconds=...

Environment Variable:

MOCKSERVER_STREAM_IDLE_TIMEOUT_SECONDS=...

Property File:

mockserver.streamIdleTimeoutSeconds=...

Example:

-Dmockserver.streamIdleTimeoutSeconds="120"

Adds a fixed delay (in milliseconds) to all matched expectation responses. This delay is additive — it combines with any per-action delay configured on individual expectations. For example, if an expectation has a 100ms delay and the global delay is 200ms, the total delay is 300ms.

This is useful for simulating network latency across all mocked endpoints without having to configure delay on each expectation individually.

Type: long Default: null (no global delay)

Java Code:

ConfigurationProperties.globalResponseDelayMillis(Long millis)

System Property:

-Dmockserver.globalResponseDelayMillis=...

Environment Variable:

MOCKSERVER_GLOBAL_RESPONSE_DELAY_MILLIS=...

Property File:

mockserver.globalResponseDelayMillis=...

Example:

-Dmockserver.globalResponseDelayMillis="200"
 

Liveness Configuration:

Path to support HTTP GET requests for status response (also available on PUT /mockserver/status).

If this value is not modified then only PUT /mockserver/status but is a none blank value is provided for this value then GET requests to this path will return the 200 Ok status response showing the MockServer version and bound ports.

A GET request to this path will be matched before any expectation matching or proxying of requests.

Type: string Default: null

Java Code:

ConfigurationProperties.livenessHttpGetPath(String livenessPath)

System Property:

-Dmockserver.livenessHttpGetPath=...

Environment Variable:

MOCKSERVER_LIVENESS_HTTP_GET_PATH=...

Property File:

mockserver.livenessHttpGetPath=...

Example:

-Dmockserver.livenessHttpGetPath="/liveness/probe"
 

MCP (Model Context Protocol) Configuration:

Enable or disable the MCP (Model Context Protocol) endpoint at /mockserver/mcp.

When enabled, MockServer exposes a JSON-RPC 2.0 endpoint implementing the MCP Streamable HTTP transport, allowing AI coding assistants to interact with MockServer programmatically — creating expectations, verifying requests, retrieving traffic, and debugging mismatches.

The MCP endpoint enforces the same control plane authentication (mTLS and/or JWT) as the REST API.

Type: boolean Default: true

Java Code:

ConfigurationProperties.mcpEnabled(boolean enable)

System Property:

-Dmockserver.mcpEnabled=...

Environment Variable:

MOCKSERVER_MCP_ENABLED=...

Property File:

mockserver.mcpEnabled=...

Example:

-Dmockserver.mcpEnabled="false"
 

gRPC Configuration:

Enable or disable gRPC protocol support. When enabled and proto descriptors are loaded (via grpcDescriptorDirectory, grpcProtoDirectory, or the PUT /mockserver/grpc/descriptors REST API), MockServer intercepts gRPC requests on HTTP/2 connections, converts protobuf to JSON, and routes them through the standard expectation matching engine. Without loaded descriptors, gRPC interception is not active even when this property is true.

Type: boolean Default: true

Java Code:

ConfigurationProperties.grpcEnabled(boolean enable)

System Property:

-Dmockserver.grpcEnabled=...

Environment Variable:

MOCKSERVER_GRPC_ENABLED=...

Property File:

mockserver.grpcEnabled=...

Example:

-Dmockserver.grpcEnabled="false"

Directory containing pre-compiled proto descriptor set files (.dsc or .desc). MockServer loads all descriptor files from this directory at startup and registers their services for gRPC mocking.

Generate descriptor files using protoc --descriptor_set_out=service.dsc --include_imports service.proto.

Type: string Default: null

Java Code:

ConfigurationProperties.grpcDescriptorDirectory(String directory)

System Property:

-Dmockserver.grpcDescriptorDirectory=...

Environment Variable:

MOCKSERVER_GRPC_DESCRIPTOR_DIRECTORY=...

Property File:

mockserver.grpcDescriptorDirectory=...

Example:

-Dmockserver.grpcDescriptorDirectory="/path/to/descriptors"

Directory containing .proto source files. MockServer compiles these files at startup using protoc and registers their services for gRPC mocking. Requires protoc to be available on the system PATH (or configured via grpcProtocPath).

Type: string Default: null

Java Code:

ConfigurationProperties.grpcProtoDirectory(String directory)

System Property:

-Dmockserver.grpcProtoDirectory=...

Environment Variable:

MOCKSERVER_GRPC_PROTO_DIRECTORY=...

Property File:

mockserver.grpcProtoDirectory=...

Example:

-Dmockserver.grpcProtoDirectory="/path/to/protos"

Path to the protoc compiler binary. Only needed when using grpcProtoDirectory to compile .proto files at startup. If protoc is on the system PATH, the default value works without configuration.

Type: string Default: "protoc"

Java Code:

ConfigurationProperties.grpcProtocPath(String path)

System Property:

-Dmockserver.grpcProtocPath=...

Environment Variable:

MOCKSERVER_GRPC_PROTOC_PATH=...

Property File:

mockserver.grpcProtocPath=...

Example:

-Dmockserver.grpcProtocPath="/usr/local/bin/protoc"
 

DNS Configuration:

Enable or disable the DNS mock server. When enabled, MockServer starts a UDP DNS server that matches incoming DNS queries against expectations. DNS expectations use DnsRequestDefinition for matching and DnsResponse for responses. Supported record types: A, AAAA, CNAME, MX, SRV, TXT, PTR.

Type: boolean Default: false

Java Code:

ConfigurationProperties.dnsEnabled(boolean enable)

System Property:

-Dmockserver.dnsEnabled=...

Environment Variable:

MOCKSERVER_DNS_ENABLED=...

Property File:

mockserver.dnsEnabled=...

Example:

-Dmockserver.dnsEnabled="true"

The UDP port for the DNS mock server. Set to 0 to let the operating system assign an ephemeral port. Use MockServer.getDnsPort() to retrieve the actual bound port at runtime.

Type: integer Default: 0

Java Code:

ConfigurationProperties.dnsPort(int port)

System Property:

-Dmockserver.dnsPort=...

Environment Variable:

MOCKSERVER_DNS_PORT=...

Property File:

mockserver.dnsPort=...

Example:

-Dmockserver.dnsPort="5353"
 

Control Plane Authentication Configuration:

Enable mTLS authentication for control plane interactions (i.e. create expectations, clear, reset, verify, retrieve, stop, etc)

If enabled then all control plane requests need to be received over a mTLS connection where the client's X509 certificates will be validated using the controlPlaneTLSMutualAuthenticationCAChain

It is possible to enable both controlPlaneJWTAuthenticationRequired and controlPlaneTLSMutualAuthenticationRequired but the mTLS will be checked first.

Type: boolean Default: false

Java Code:

ConfigurationProperties.controlPlaneTLSMutualAuthenticationRequired(boolean controlPlaneTLSMutualAuthenticationRequired)

System Property:

-Dmockserver.controlPlaneTLSMutualAuthenticationRequired=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_MUTUAL_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.controlPlaneTLSMutualAuthenticationRequired=...

Example:

-Dmockserver.controlPlaneTLSMutualAuthenticationRequired="true"

File system path or classpath location of the CA (i.e. trust) chain to use to validate client X509 certificates if controlPlaneTLSMutualAuthenticationRequired is enabled

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneTLSMutualAuthenticationCAChain(String controlPlaneTLSMutualAuthenticationCAChain)

System Property:

-Dmockserver.controlPlaneTLSMutualAuthenticationCAChain=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.controlPlaneTLSMutualAuthenticationCAChain=...

Example:

-Dmockserver.controlPlaneTLSMutualAuthenticationCAChain="/some/existing/path"

File system path or classpath location of the private key used by MockServerClient when controlPlaneTLSMutualAuthenticationRequired is enabled to ensure control plane request are correctly authorised

For control plane requests to be authorised the private key controlPlanePrivateKeyPath and certificate controlPlanePrivateKeyPath must:

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlanePrivateKeyPath(String controlPlanePrivateKeyPath)

System Property:

-Dmockserver.controlPlanePrivateKeyPath=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_PRIVATE_KEY_PATH=...

Property File:

mockserver.controlPlanePrivateKeyPath=...

Example:

-Dmockserver.controlPlanePrivateKeyPath="/some/existing/path"

File system path or classpath location of the certificate used by MockServerClient when controlPlaneTLSMutualAuthenticationRequired is enabled to ensure control plane request are correctly authorised

For control plane requests to be authorised the private key controlPlanePrivateKeyPath and certificate controlPlanePrivateKeyPath must:

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneX509CertificatePath(String controlPlaneX509CertificatePath)

System Property:

-Dmockserver.controlPlaneX509CertificatePath=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_X509_CERTIFICATE_PATH=...

Property File:

mockserver.controlPlaneX509CertificatePath=...

Example:

-Dmockserver.controlPlaneX509CertificatePath="/some/existing/path"

Enable JWT authentication for control plane interactions (i.e. create expectations, clear, reset, verify, retrieve, stop, etc)

If enabled then all control plane requests need and JWT via a authorization header which is validated using the controlPlaneJWTAuthenticationJWKSource

It is possible to enable both controlPlaneJWTAuthenticationRequired and controlPlaneTLSMutualAuthenticationRequired but the mTLS will be checked first.

Type: boolean Default: false

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationRequired(boolean controlPlaneJWTAuthenticationRequired)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationRequired=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.controlPlaneJWTAuthenticationRequired=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationRequired="true"

URL, file system path or classpath location of the JWK source when controlPlaneJWTAuthenticationRequired is enabled to validate JWT signatures

For control plane requests to be authorised:

  • they must include an authorization header, with a Bearer auth scheme, containing a JWT
  • the JWT should be validated by a key in the JWK source

For details of JWK see the JWK specification

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationJWKSource(String controlPlaneJWTAuthenticationJWKSource)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationJWKSource=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_JWK_SOURCE=...

Property File:

mockserver.controlPlaneJWTAuthenticationJWKSource=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationJWKSource="/some/existing/path"

Audience claim (i.e. aud) required when JWT authentication is enabled for control plane requests

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationExpectedAudience(String controlPlaneJWTAuthenticationExpectedAudience)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationExpectedAudience=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_EXPECTED_AUDIENCE=...

Property File:

mockserver.controlPlaneJWTAuthenticationExpectedAudience=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationExpectedAudience="/some/existing/path"

Matching claims expected when JWT authentication is enabled for control plane requests

Value should be string with comma separated key=value items, for example: scope=internal public,sub=some_subject

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationMatchingClaims(String controlPlaneJWTAuthenticationMatchingClaims)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationMatchingClaims=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_MATCHING_CLAIMS=...

Property File:

mockserver.controlPlaneJWTAuthenticationMatchingClaims=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationMatchingClaims="/some/existing/path"

Required claims that should exist (i.e. with any value) when JWT authentication is enabled for control plane requests

Value should be string with comma separated values, for example: scope,sub

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationRequiredClaims(String controlPlaneJWTAuthenticationRequiredClaims)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationRequiredClaims=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_REQUIRED_CLAIMS=...

Property File:

mockserver.controlPlaneJWTAuthenticationRequiredClaims=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationRequiredClaims="/some/existing/path"
 

TLS Configuration:

The following diagram shows where TLS/mTLS configuration settings are used:

MockServer HTTPS & TLS

 

Inbound TLS (for Received Requests)

Dynamic Inbound Certificate Authority X.509 & Private Key

Enable dynamic creation of Certificate Authority X.509 Certificate and Private Key

Enable this property to increase the security of trusting the MockServer Certificate Authority X.509 by ensuring a local dynamic value is used instead of the public value in the MockServer git repo.

These PEM files will be created and saved in the directory specified with configuration property directoryToSaveDynamicSSLCertificate.

A Certificate Authority X.509 Certificate and Private Key will only be created if the files used to save them are not already present. Therefore, if MockServer is re-started multiple times with the same value for directoryToSaveDynamicSSLCertificate. the Certificate Authority X.509 Certificate and Private Key will only be created once.

Type: boolean Default: false

Java Code:

ConfigurationProperties.dynamicallyCreateCertificateAuthorityCertificate(boolean enable)

System Property:

-Dmockserver.dynamicallyCreateCertificateAuthorityCertificate=...

Environment Variable:

MOCKSERVER_DYNAMICALLY_CREATE_CERTIFICATE_AUTHORITY_CERTIFICATE=...

Property File:

mockserver.dynamicallyCreateCertificateAuthorityCertificate=...

Example:

-Dmockserver.dynamicallyCreateCertificateAuthorityCertificate="true"

Directory used to save the dynamically generated Certificate Authority X.509 Certificate and Private Key.

This directory will only be used if MockServer is configured to create a dynamic Certificate Authority X.509 certificate and private key using dynamicallyCreateCertificateAuthorityCertificate.

Type: string Default: null

Java Code:

ConfigurationProperties.directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate)

System Property:

-Dmockserver.directoryToSaveDynamicSSLCertificate=...

Environment Variable:

MOCKSERVER_CERTIFICATE_DIRECTORY_TO_SAVE_DYNAMIC_SSL_CERTIFICATE=...

Property File:

mockserver.directoryToSaveDynamicSSLCertificate=...

Example:

-Dmockserver.directoryToSaveDynamicSSLCertificate="/some/existing/path"

Proactively initialise TLS during start to ensure that if dynamicallyCreateCertificateAuthorityCertificate is enabled the Certificate Authority X.509 Certificate and Private Key will be created during start up and not when the first TLS connection is received.

This setting will also ensure any configured private key and X.509 will be loaded during start up and not when the first TLS connection is received to give immediate feedback on any related TLS configuration errors.

Type: boolean Default: false

Java Code:

ConfigurationProperties.proactivelyInitialiseTLS(boolean enable)

System Property:

-Dmockserver.proactivelyInitialiseTLS=...

Environment Variable:

MOCKSERVER_PROACTIVELY_INITIALISE_TLS=...

Property File:

mockserver.proactivelyInitialiseTLS=...

Example:

-Dmockserver.proactivelyInitialiseTLS="true"

TLS Protocol Versions

Comma separated list of TLS protocol versions to enable for both inbound and outbound TLS connections.

The default value is TLSv1,TLSv1.1,TLSv1.2 which includes TLSv1 and TLSv1.1 for backward compatibility. These older protocols are deprecated and considered insecure by most security standards.

To enable TLS 1.3, add TLSv1.3 to the list. To use only modern protocols, set the value to TLSv1.2,TLSv1.3.

Note: TLS 1.3 requires Java 11 or later. MockServer's default includes TLSv1 and TLSv1.1 for backward compatibility but you should restrict protocols to TLSv1.2 and TLSv1.3 in production-like environments.

Type: string Default: TLSv1,TLSv1.1,TLSv1.2

Java Code:

ConfigurationProperties.tlsProtocols("TLSv1.2,TLSv1.3")

System Property:

-Dmockserver.tlsProtocols=...

Environment Variable:

MOCKSERVER_TLS_PROTOCOLS=...

Property File:

mockserver.tlsProtocols=...

Example (enable TLS 1.2 and 1.3 only):

-Dmockserver.tlsProtocols="TLSv1.2,TLSv1.3"

Example (Docker environment variable):

MOCKSERVER_TLS_PROTOCOLS="TLSv1.2,TLSv1.3"

Dynamic Inbound Private Key & X.509

MockServer dynamically updates the Subject Alternative Name (SAN) values for its TLS certificate to add domain names and IP addresses from request Host headers and Host headers in expectations, this configuration setting disables this automatic update and only uses SAN value provided in TLS Subject Alternative Name Domains and TLS Subject Alternative Name IPs configuration properties.

When this property is enabled the generated X.509 Certificate and Private Key pair are saved to the directoryToSaveDynamicSSLCertificate as Certificate.pem and PKCS8PrivateKey.pem

Type: boolean Default: false

Java Code:

ConfigurationProperties.preventCertificateDynamicUpdate(boolean prevent)

System Property:

-Dmockserver.preventCertificateDynamicUpdate=...

Environment Variable:

MOCKSERVER_PREVENT_CERTIFICATE_DYNAMIC_UPDATE=...

Property File:

mockserver.preventCertificateDynamicUpdate=...

Example:

-Dmockserver.preventCertificateDynamicUpdate="true"

The domain name for auto-generate TLS certificates

Type: string Default: localhost

Java Code:

ConfigurationProperties.sslCertificateDomainName(String domainName)

System Property:

-Dmockserver.sslCertificateDomainName=...

Environment Variable:

MOCKSERVER_SSL_CERTIFICATE_DOMAIN_NAME=...

Property File:

mockserver.sslCertificateDomainName=...

Example:

-Dmockserver.sslCertificateDomainName="localhost"

The Subject Alternative Name (SAN) domain names for auto-generate TLS certificates as a comma separated list

Type: string Default: localhost

Java Code:

ConfigurationProperties.addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains)
or
ConfigurationProperties.clearSslSubjectAlternativeNameDomains()

System Property:

-Dmockserver.sslSubjectAlternativeNameDomains=...

Environment Variable:

MOCKSERVER_SSL_SUBJECT_ALTERNATIVE_NAME_DOMAINS=...

Property File:

mockserver.sslSubjectAlternativeNameDomains=...

Example:

-Dmockserver.sslSubjectAlternativeNameDomains="localhost,www.foo.bar"

The Subject Alternative Name (SAN) IP addresses for auto-generate TLS certificates as a comma separated list

Type: string Default: 127.0.0.1,0.0.0.0

Java Code:

ConfigurationProperties.addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps)
or
ConfigurationProperties.clearSslSubjectAlternativeNameIps()

System Property:

-Dmockserver.sslSubjectAlternativeNameIps=...

Environment Variable:

MOCKSERVER_SSL_SUBJECT_ALTERNATIVE_NAME_IPS=...

Property File:

mockserver.sslSubjectAlternativeNameIps=...

Example:

-Dmockserver.sslSubjectAlternativeNameIps="127.0.0.1,0.0.0.0"

Fixed (i.e. Custom) Inbound Certificate Authority X.509 & Private Key

Location of custom file for Certificate Authority for TLS, the private key must be a PKCS#8 or PKCS#1 PEM file and must match the TLS Certificate Authority X.509 Certificate.

To convert a PKCS#1 PEM file (i.e. default for Bouncy Castle) to a PKCS#8 PEM file the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

Type: string Default: null

Java Code:

ConfigurationProperties.certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey)

System Property:

-Dmockserver.certificateAuthorityPrivateKey=...

Environment Variable:

MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY=...

Property File:

mockserver.certificateAuthorityPrivateKey=...

Example:

-Dmockserver.certificateAuthorityPrivateKey="/some/existing/path"

Location of custom file for Certificate Authority for TLS, the certificate must be a X.509 PEM file and must match the TLS Certificate Authority Private Key.

Type: string Default: null

Java Code:

ConfigurationProperties.certificateAuthorityCertificate(String certificateAuthorityCertificate)

System Property:

-Dmockserver.certificateAuthorityCertificate=...

Environment Variable:

MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE=...

Property File:

mockserver.certificateAuthorityCertificate=...

Example:

-Dmockserver.certificateAuthorityCertificate="/some/existing/path"

Fixed (i.e. Custom) Inbound Private Key & X.509

File system path or classpath location of a fixed custom private key for TLS connections into MockServer.

The private key must be a PKCS#8 or PKCS#1 PEM file and must be the private key corresponding to the x509CertificatePath X.509 (public key) configuration.

The certificateAuthorityCertificate configuration must be the Certificate Authority for the corresponding X.509 certificate (i.e. able to valid its signature), see: x509CertificatePath.

To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

This configuration will be ignored unless x509CertificatePath is also set.

Type: string Default: null

Java Code:

ConfigurationProperties.privateKeyPath(String privateKeyPath)

System Property:

-Dmockserver.privateKeyPath=...

Environment Variable:

MOCKSERVER_TLS_PRIVATE_KEY_PATH=...

Property File:

mockserver.privateKeyPath=...

Example:

-Dmockserver.privateKeyPath="/some/existing/path"

File system path or classpath location of a fixed custom X.509 Certificate for TLS connections into MockServer

The certificate must be a X.509 PEM file and must be the public key corresponding to the privateKeyPath private key configuration.

The certificateAuthorityCertificate configuration must be the Certificate Authority for this certificate (i.e. able to valid its signature).

This configuration will be ignored unless privateKeyPath is also set.

Type: string Default: null

Java Code:

ConfigurationProperties.x509CertificatePath(String x509CertificatePath)

System Property:

-Dmockserver.x509CertificatePath=...

Environment Variable:

MOCKSERVER_TLS_X509_CERTIFICATE_PATH=...

Property File:

mockserver.x509CertificatePath=...

Example:

-Dmockserver.x509CertificatePath="/some/existing/path"

Inbound mTLS Client Authentication (for Received Requests)

Require mTLS (also called client authentication and two-way TLS) for all TLS connections / HTTPS requests to MockServer

Type: boolean Default: false

Java Code:

ConfigurationProperties.tlsMutualAuthenticationRequired(boolean enable)

System Property:

-Dmockserver.tlsMutualAuthenticationRequired=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.tlsMutualAuthenticationRequired=...

Example:

-Dmockserver.tlsMutualAuthenticationRequired="true"

File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X.509 PEM file.

This certificate chain will be used if MockServer performs mTLS (client authentication) for inbound TLS connections because tlsMutualAuthenticationRequired is enabled

This configuration property is also used for MockServerClient to trust outbound TLS X.509 certificates i.e. TLS connections to MockServer

Type: string Default: null

Java Code:

ConfigurationProperties.tlsMutualAuthenticationCertificateChain(String certificateChain)

System Property:

-Dmockserver.tlsMutualAuthenticationCertificateChain=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.tlsMutualAuthenticationCertificateChain=...

Example:

-Dmockserver.tlsMutualAuthenticationCertificateChain="/some/existing/path"


 

Outbound Client TLS/mTLS (for Forwarded or Proxied Requests)

Configure trusted set of certificates for forwarded or proxied requests (i.e. TLS connections out of MockServer).

MockServer will only be able to establish a TLS connection to endpoints that have a trusted X.509 certificate according to the trust manager type, as follows:

  • ANY - Insecure will trust all X.509 certificates and not perform host name verification.
  • JVM - Will trust all X.509 certificates trust by the JVM.
  • CUSTOM - Will trust all X.509 certificates specified in forwardProxyTLSCustomTrustX509Certificates configuration value.

Type: string Default: ANY

Java Code:

ConfigurationProperties.forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType)

System Property:

-Dmockserver.forwardProxyTLSX509CertificatesTrustManagerType=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_X509_CERTIFICATES_TRUST_MANAGER_TYPE=...

Property File:

mockserver.forwardProxyTLSX509CertificatesTrustManagerType=...

Example:

-Dmockserver.forwardProxyTLSX509CertificatesTrustManagerType="CUSTOM"

Fixed (i.e. Custom) Outbound CA X.509, Private Key & X.509

File system path or classpath location of custom file for trusted X.509 Certificate Authority roots for forwarded or proxied requests (i.e. TLS connections out of MockServer), the certificate chain must be a X.509 PEM file.

MockServer will only be able to establish a TLS connection to endpoints that have an X.509 certificate chain that is signed by one of the provided custom certificates, i.e. where a path can be established from the endpoints X.509 certificate to one or more of the custom X.509 certificates provided.

This configuration only take effect if forwardProxyTLSX509CertificatesTrustManagerType is configured as CUSTOM otherwise this value is ignored.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates)

System Property:

-Dmockserver.forwardProxyTLSCustomTrustX509Certificates=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_CUSTOM_TRUST_X509_CERTIFICATES=...

Property File:

mockserver.forwardProxyTLSCustomTrustX509Certificates=...

Example:

-Dmockserver.forwardProxyTLSCustomTrustX509Certificates="/some/existing/path"

File system path or classpath location of custom Private Key for forwarded or proxied requests (i.e. TLS connections out of MockServer), the private key must be a PKCS#8 or PKCS#1 PEM file

To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

This private key will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyPrivateKey(String privateKey)

System Property:

-Dmockserver.forwardProxyPrivateKey=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_PRIVATE_KEY=...

Property File:

mockserver.forwardProxyPrivateKey=...

Example:

-Dmockserver.forwardProxyPrivateKey="/some/existing/path"

File system path or classpath location of custom X.509 Certificate Chain for forwarded or proxied requests (i.e. TLS connections out of MockServer), the certificates must be a X.509 PEM file

This certificate chain will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyCertificateChain(String certificateChain)

System Property:

-Dmockserver.forwardProxyCertificateChain=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_X509_CERTIFICATE_CHAIN=...

Property File:

mockserver.forwardProxyCertificateChain=...

Example:

-Dmockserver.forwardProxyCertificateChain="/some/existing/path"
 

MockServer Client

File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) MockServer X.509 Certificates, the certificate chain must be a X.509 PEM file. This certificate chain will only be used if MockServerClient performs TLS to calls to MockServer.

This settings is particularly used when connecting to MockServer via a load-balancer or other TLS terminating network infrastructure with its own X.509 Certificate.

This configuration property is also used for MockServer to trust inbound mTLS client authentication X.509 certificates

Type: string Default: null

Java Code:

ConfigurationProperties.tlsMutualAuthenticationCertificateChain(String certificateChain)

System Property:

-Dmockserver.tlsMutualAuthenticationCertificateChain=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.tlsMutualAuthenticationCertificateChain=...

Example:

-Dmockserver.tlsMutualAuthenticationCertificateChain="/some/existing/path"