Docker Desktop Brew



MockServer is flexible and support numerous usage patterns.

  1. Docker Desktop Brewery
  2. Docker Desktop Brewing

Docker Desktop for Windows. 原文 、ウェブ版原文 2020年6月4日現在の情報です。 Windows 10 Pro で Docker Desktop をセットアップする手順については、別途記事をまとめ ています。. Command-line completion. Estimated reading time: 3 minutes. Compose comes with command completion for the bash and zsh shell. Install command completion Bash. Make sure bash completion is installed. A little more about Docker and containers: Docker is a containerization platform that packages your application and all its dependencies together in the form of a docker container. It’s a set of platform-as-a-service products designed to solve the many challenges created by the growing DevOps trend. Give feedback and get help. To get help from the community, review current user topics, join or start a discussion, log on to our Docker Desktop for Mac forum. To report bugs or problems, log on to Docker Desktop for Mac issues on GitHub, where you can review community reported issues, and file new ones. Before: I had docker-compose version: docker-compose version 1.21.2, build a133471 So to upgrade to latest non-RC version, I found this to work in order to upgrade: 1) apt install python-pip to install PIP then pip install docker-compose to install the latest and then to check the version: docker-compose -version which gave me: docker-compose.

MockServer can be run:

  • programmatically via a Java API in an @Before or @After method
  • using a JUnit 4 @Rule via a @Rule annotated field in a JUnit 4 test
  • using a JUnit 5 Test Extension via a @ExtendWith annotated JUnit 5 class
  • using a Spring Test Execution Listener via a @MockServerTest annotated test class
  • as a Docker container in any Docker enabled environment
  • via a Helm chart in any Kubernetes environment
  • from the command line as a stand-alone process in a test environment
  • via a Maven Plugin as part of a Maven build cycle
  • as a Node.js (npm) module from any Node.js code
  • as a Grunt plugin as part of a Grunt build cycle
  • as a deployable WAR to an existing application server

To simplify configuration all versions (except the deployable WAR) use a single port to support the control plane and data plane in HTTP, HTTPS or SOCKS.

MockServer is available in the following formats:

  • Helm chart for Kubernetes
  • deployable WAR that runs on JEE web servers

It is also possible to build and run MockServer directly from source code

MockServer UI:

Docker desktop brewing

MockServer has a UI that can be used to view the internal state within MockServer, including:

Maven Plugin

Docker

To run MockServer as part of your build add the following plugin to your pom.xml:

This will start MockServer during the process-test-classes phase and will stop MockServer during the verify phase. For more details about Maven build phases see: Introduction to the Build Lifecycle.

This ensures that any integration tests you run during the test or integration-test phases can use MockServer on the port specified.

It is also possible to run MockServer as a forked JVM using the runForked and stopForked goals as follows:

Stop MockServer Even When Tests Fail

If you use the runForked goal as above and the test phase fails (because a test has failed) MockServer will not be stopped as Maven does not run any more phases after a phase has failed. In the case above the verify phase is not run if a test fails so the forked MockServer will not be stopped.

If you want to ensure MockServer is stopped even when there are test failures make sure you use start and stop goals as these run MockServer on a separate thread that is stopped however maven exits (even if a test fails).

Alternatively a TestListener can be used with maven-surefire-plugin to ensure that MockServer is stopped even when a test fails, as follows:

The Maven plugin can also be used from the command line to start and stop MockServer, as follows:

To run MockServer synchronously and block:

To run MockServer asynchronously as a forked JVM:

To stop a forked instance of MockServer running on the same machine:

The stopForked goal does assumes that MockServer is running on the same physical machine as it uses 127.0.0.1 to communicate with MockServer stop socket.

The Maven plugin has the following goals:

  • start - start MockServer, do not block, but stop when build ends
  • stop - stop a MockServer started earlier as part of the current build
  • run - run MockServer and block waiting for requests (timeout config if provided limits how long to block for)
  • runForked - run MockServer as separate forked JVM, do not block, stay alive when build ends
  • stopForked - stop a forked MockServer, previously started by a runForked goal

The Maven plugin can be configured with the following properties:

  • serverPort - The port the MockServer listens for incoming request. Port unification is used to support both HTTP and HTTPS on the same port (required: true)
  • proxyRemotePort - The port proxied requests are forwarded to (required: false)
  • proxyRemoteHost - The host proxied requests are forwarded to (required: false)
  • timeout - How long to block waiting for MockServer, after the timeout the plugin will shutdown MockServer, used by run goal, 0 means wait indefinitely (required: false, default: 0)
  • logLevel - The logging level (required: false, default: INFO)
  • skip - Prevent the plugin from running (required: false, default: false)
  • initializationClass - To enable the creation of default expectations a class can be specified to initialize expectations in MockServer, this class must implement org.mockserver.client.initialize.PluginExpectationInitializer interface. The initializeExpectations(MockServerClient mockServerClient) method will be called once MockServer has been started. Note: that the plugin must be started during the process-test-classes to ensure that the initialization class has been compiled from either src/main/java or src/test/java locations. In addition the initializer can only be used with start and run goals, it will not work with the runForked goal as a JVM is forked with a separate classpath. (required: false, default: false)

Client API - starting and stopping

Use the client API to run MockServer programmatically.

First add the following maven dependency:

To start the server or proxy create a client, for example by using one of the start factory methods ClientAndServer.startClientAndServer as follows:

Add includes:

Add fields:

Use factory method to start server and client when appropriate, for example in @Before method:

Stop server and client when appropriate, for example in @After method:

The mockserver-example project contains an example test called BookPageIntegrationTest that demonstrates a fully working example.

Running MockServer via a JUnit 4 @Rule

MockServer can be run using the MockServerRule. The MockServerRule starts MockServer (for both mocking and proxying) on a free port before the any test runs and stops MockServer after all tests have completed.

An instance of MockServerClient is assigned to any field in the unit test of type org.mockserver.client.MockServerClient. Alternatively an instance of MockServerClient can be retrieved from the MockServerRule using the method getClient().

The MockServerRule can be added to your project by including the following maven dependency:

Any test method can now use the mockServerClient field to create expectation or verify requests.

The MockServerRule has the following constructors:

Running MockServer via a JUnit 5 Test Extension

MockServer can be run using the Test Extension MockServerExtension. The MockServerExtension starts MockServer (for both mocking and proxying) before the any test runs and stops MockServer after all tests have completed.

The port(s) MockServer uses can be controlled using MockServerSettings

An instance of MockServerClient or ClientAndServer is injected into any method using Parameter Resolution this includes: constructors, lifecycle methods (like @BeforeEach / @BeforeAll), or test methods.

The MockServerExtension Test Extension can be added to your project by including the following maven dependency:

The following code examples show how to use the MockServerExtension Test Extension.

Running MockServer via Spring TestExecutionListener @MockServerTest

MockServer can be run using @MockServerTest. The mockserver-spring-test-listener dependency registers a Spring TestExecutionListener which starts MockServer on a free port if the test class is annotated with @MockServerTest. MockServer is reset after each test and closed after all tests via a shutdown hook.

As the MockServer instance is shared between all test classes @MockServerTest does not support parallel test execution, unless each test uses a unique value in each request matcher.

The TestExecutionListener with @MockServerTest can be added to your project by including the following maven dependency:

An instance of MockServerClient is assigned to any field in the unit test of type org.mockserver.client.MockServerClient.

If you want to configure a client (Spring Bean) to use MockServer you can create a test property with ${mockServerPort} placeholder. This is replaced by the chosen free port for MockServer.

The free port itself is also added as test property and can be retrieved with @MockServerPort.

Running From Command Line

MockServer can be run from the command line in the following ways:

  • using homebrew i.e. brew install mockserver && mockserver
  • using java directly i.e. java -jar mockserver-netty-5.11.1-jar-with-dependencies.jar
  • using maven plugin i.e. mvn org.mock-server:mockserver-maven-plugin:5.11.1:runForked
  • using docker i.e. docker run -d --rm -p mockserver/mockserver

Running From Command Line - Using Homebrew

Homebrew, a packaging manager for OS X (i.e. Apple Mac), can be used to install MockServer, as follows:

Docker Desktop Brewery

The MockServer formula in Homebrew performs the following actions:

  1. installed the binaries and scripts
  2. creates the log directory
  3. add the scripts to the PATH variable

Once the MockServer has been installed by Homebrew it is available from any command shell as the mockserver command

The mockserver command supports the following options:

For example run the MockServer, as follows:

Running From Command Line - Using Java

MockServer can be run directly from the command line using java directly as follow:

  1. download mockserver-netty-5.11.1-jar-with-dependencies.jar from Maven Central

  2. java -jar <path to mockserver-netty-5.11.1-jar-with-dependencies.jar> -serverPort <port>

The command line supports the following options:

For example:

All interactions with the MockServer are logged including setting up expectations, matching expectations, clearing expectations and verifying requests. This log information can be particularly helpful when trying to debug why a test is failing or expectations are not being matched.

The argument logLevel can be used to set the log level, as shown above. It is also possible to further customise where loggers send log events by overriding the default logging configuration.

Running From Command Line - Using Maven Plugin

MockServer can be run directly from the command line and using the mockserver-maven-plugin as follow:

When run from the command line the Maven plugin can be configured with the following properties:

  • mockserver.serverPort - The port the MockServer listens for incoming request. Port unification is used to support both HTTP and HTTPS and proxying on the same port (required: false)
  • mockserver.logLevel - The logging level (required: false, default: INFO)

The runForked goal of the mockserver-maven-plugin will fork a JVM process containing the Netty based MockServer. To stop the forked JVM process use the stopForked goal, as follows:

For more information on the mockserver-maven-plugin see the section on MockServer Maven Plugin

Web Archive (WAR)

To run as a WAR deployed on any JEE web server:

  1. download mockserver-war-5.11.1.war from Maven Central
  2. deploy mockserver-war-5.11.1.war to any JEE web server

WAR Context Path

The WAR context path is ignored from all request matching for path.

The MockServerClient constructor includes an argument for the context path that the WAR has been deployed to, as follows:

NPM Module & MockServer Grunt Plugin

The node module can be used to start and stop MockServer as a node module or as a Grunt plugin.

You may install this plugin / node module with the following command:

Node Module

To start or stop the MockServer from any Node.js code you need to import this module using require('mockserver-node') as follows:

Then you can use either the start_mockserver or stop_mockserver functions as follows:

MockServer uses port unification to support HTTP, HTTPS, SOCKS, HTTP CONNECT, Port Forwarding Proxying on the same port. A client can then connect to the single port with both HTTP and HTTPS as the socket will automatically detected SSL traffic and decrypt it when required.

Grunt Plugin

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins.

In your project's Gruntfile, add a section named start_mockserver and stop_mockserver to the data object passed into grunt.initConfig().

The following example will result in a both a MockServer being started on ports 1080 and 1080.

Request Log

The request log will only be captured in MockServer if the log level is INFO (or more verbose, i.e. DEBUG or TRACE) therefore to capture the request log and use the /retrieve endpoint ensure either the option trace: true or the command line switch --verbose is set.Docker

Grunt Plugin & NPM Module Options

options.serverPort

Type: Integer Default: undefined

The HTTP, HTTPS, SOCKS and HTTP CONNECT port(s) for both mocking and proxying requests. Port unification is used to support all protocols for proxying and mocking on the same port(s). Supports comma separated list for binding to multiple ports.

options.proxyRemotePort

Type: Integer Default: undefined

Optionally enables port forwarding mode. When specified all requests received will be forwarded to the specified port, unless they match an expectation.

options.proxyRemoteHost

Type: String Default: undefined

Docker Desktop Brew

Specified the host to forward all proxy requests to when port forwarding mode has been enabled using the proxyRemotePort option. This setting is ignored unless proxyRemotePort has been specified. If no value is provided for proxyRemoteHost when proxyRemotePort has been specified, proxyRemoteHost will default to 'localhost'.

options.artifactoryHost

Type: String Default: oss.sonatype.org

This value specifies the name of the artifact repository host.

options.artifactoryPath

Type: String Default: /content/repositories/releases/org/mock-server/mockserver-netty/

This value specifies the path to the artifactory leading to the mockserver-netty jar with dependencies.

options.mockServerVersion

Type: String Default: 5.11.1

This value specifies the artifact version of MockServer to download.

Note: It is also possible to specify a SNAPSHOT version to get the latest unreleased changes.

options.verbose

Type: Boolean Default: false

This value indicates whether the MockServer logs should be written to the console. In addition to logging additional output from the grunt task this options also sets the logging level of the MockServer to INFO. At INFO level all interactions with the MockServer including setting up expectations, matching expectations, clearing expectations and verifying requests are written to the log.

Note: It is also possible to use the --verbose command line switch to enabled verbose level logging from the command line.

options.trace

Type: Boolean Default: false

Docker Desktop Brewing

This value sets the logging level of the MockServer to TRACE. At TRACE level (in addition to INFO level information) all matcher results, including when specific matchers fail (such as HeaderMatcher) are written to the log.

options.javaDebugPort

Type: Integer Default: undefined

This value indicates whether Java debugging should be enabled and if so which port the debugger should listen on. When this options is provided the following additional option is passed to the JVM:

Note:suspend=y is used so the MockServer will pause until the debugger is attached. The grunt task will wait 50 seconds for the debugger to be attached before it exits with a failure status.

options.jvmOptions

Type: String Default: undefined

This value allows any system properties to be passed to the JVM that runs MockServer, for example:

options.startupRetries

Type: Integer Default: if javaDebugPort is not set 110, but if javaDebugPort is set 500

This value indicates the how many times we will call the check to confirm if the mock server started up correctly. It will default to 110 which will take about 11 seconds to complete, this is normally long enough for the server to startup. The server can take longer to start up if Java debugging is enabled so this will default to 500. The default will, in some cases, need to be overridden as the JVM may take longer to start up on some architectures, e.g. Mac seems to take a little longer.

Docker Container

The typical sequence for running the MockServer docker image is as follows:In addition it is possible to customise how the container is run.

Install Docker

To install Docker see the installation instructions.

Pull MockServer Image

To pull the MockServer Docker image use the pull command, as follows:

This is not strictly necessary as the image will be automatically pulled if it does not exist when the run command is used. However, using the pull command will ensure the latest version of the image is downloaded.

Run MockServer Container

Then to run MockServer as a Docker container run the following command:

The -P switch in this command tells Docker to map all ports exported by the MockServer container to dynamically allocated ports on the host machine.

To view information about the MockServer container, including which dynamic ports have been used run the following command:

Configure Port Mapping

This MockServer docker container exports the following port:

  • serverPort 1080

To specify which ports (on the host machine) should be mapped to the MockServer docker container use the -p<host port>:<container port> option, as follows:

For example:

Modifying Default Command

By default when the MockServer container runs it executes a bash script passing three command line options, as follows

This can be modified to change the command line options passed to the MockServer for example:

Interactive Shell

MockServer uses distroless as its based container for both size and security and so does not contain an interactive shell. This minimises the likelihood of vulnerabilities and to reduces the attack surface by ensuring only the JVM and MockServer code is inside the container.

Detailed MockServer Configuration

To support configuring MockServer a mockserver.properties will be loaded from /config directory if it exists.

A mockserver.properties configuration file and other related configuration files such as json expectation initialization, or custom TLS CA, X.509 Certificate or Private Key should be mapping into the /config directory.

For example to add configuration files in the current directory, such as mockserver.properties, map $(pwd) into /config, as follows:

See MockServer Configuration for details of all configuration options.

Extending MockServer Classpath

To use class callbacks or an expectation initializer class the classpath for MockServer must include the specified classes.

To support adding classes to the classpath any jar files contained in the /libs directory will be added into MockServer classpath.

For example to add all jar files in the current directory, map $(pwd) into /libs, as follows:

Docker Compose

MockServer can be run using docker compose by adding the container as a service.

The MockServer container uses an entrypoint, so it is possible to configure the MockServer by specifying the command line flags using by specifying the command, as follows:

It is also possible to configure the MockServer by setting environment variables, as follows:

It is also possible to configure the MockServer by mounting a volume containing a properties file or JSON expectation initializer, as follows:

Deploying MockServer Helm Chart

Desktop

To run MockServer in Kubernetes the easiest way is to use the existing MockServer helm chart.

This is available by using www.mock-server.com as a chart repo, with the following command:

OR

If you have helm chart source folder (i.e. you have the repository cloned):

The two commands above will install MockServer into a namespace called mockserver with default configuration (as per the embedded values.yaml).

MockServer will then be available on domain name mockserver.mockserver.svc.cluster.local, as long as the namespace you are calling from isn't prevented (by network policy) to call the mockserver namespace.

To view the logs:

or open the UI

To wait until the deployment is complete run:

To check the status of the deployment without waiting, run the following command and confirm the mockserver has the Running status:

Basic MockServer Configuration

Modify the arguments used to start the docker container by setting values explicitly using --set, as follows:

The following values are supported:

  • app.serverPort (default: 1080)
  • app.logLevel (default: INFO)
  • app.proxyRemoteHost (no default)
  • app.proxyRemotePort (no default)
  • app.jvmOptions (no default)
  • image.snapshot (default: false) - set true to use latest snapshot version

For example configure a proxyRemoteHost and proxyRemotePort, as follows:

Double check the correct arguments have been passed to the pod, as follows:

Detailed MockServer Configuration

If a configmap called mockserver-config exists in the same namespace this will be mapped into the MockServer container under the mountPath/config.

This configmap can be used to configure MockServer by containing a mockserver.properties file and other related configuration files such as a:

  • json expectation initialization, or
  • custom TLS CA, X.509 Certificate or Private Key

The mockserver.properties file should load these additional files from the directory /config which is the mountPath for the configmap.

See MockServer Configuration for details of all configuration options.

The mapping of the configuration configmap can be configured as follows:

  • app.mountedConfigMapName (default: mockserver-config) - name of the configuration configmap (in the same namespace) to mount
  • app.propertiesFileName (default: mockserver.properties) - name of the property file in the configmap
For example:An example of a helm chart to configure MockServer is helm/mockserver-config

Extending MockServer Classpath

To use class callbacks or an expectation initializer class the classpath for MockServer must include the specified classes.

To support adding classes to the classpath if a configmap called mockserver-config exists in the same namespace any jar files contained in this configmap will be added into MockServer classpath.

The mapping of the libs configmap can be configured as follows:

  • app.mountedLibsConfigMapName (default: mockserver-config) - name of the libs configmap (in the same namespace) to mount
For example:

MockServer URL

Local Kubernetes Cluster (i.e. minikube, microk8s)

If the service type hasn't been modified the following will provide the MockServer URL from outside the cluster.

To test the installation the following curl command should return the ports MockServer is bound to:

Docker for Desktop

Docker for Desktop automatically exposes LoadBalancer services.

On MacOS Docker for Desktop runs inside Hyperkit so the node IP address is not reachable, therefore the only way to call services is via the exposed LoadBalancer service added by Docker for Desktop.

To ensure that Docker for Desktop exposes MockServer update the service type to LoadBalancer using --set service.type=LoadBalancer and set the exposed port using --set service.port=1080, as follows:

MockServer will then be reachable on http://localhost:1080

For LoadBalancer services it is possible to query kubernetes to programmatically determine the MockServer base URL as follows:

Outside Remote Kubernetes Cluster (i.e. Azure AKS, AWS EKS, etc) via Port Forward

Inside Kubernetes Cluster

If a DNS server has been installed in the Kubernetes cluster the following DNS name should be available mockserver.<namespace>.svc.cluster.local, i.e. mockserver.mockserver.svc.cluster.local

Helm Delete

To completely remove the chart:

Build & Run From Source

MockServer is written in Java and built using maven. The maven wrapper is used so maven does not need to be installed but Java JDK 8 or higher does need to be installed.

First clone the repository as follows:

Next use maven to build an executable jar containing all dependencies as follows:

This will produce a jar file under the target directory called, as follows:

Run MockServer then using the executable jar as per the instruction above in Running From The Command Line