Recipes

Mock Microservices by Host

In a staging cluster or a local compose setup, an app talks to several services, and you rarely want to fake all of them. This recipe puts one Mocko in front of two services using host blocks: each service keeps its real behavior except for the routes you override.

The recipe

host "billing" {
name = "Billing Service"
source = "billing.local"
destination = "https://demo-billing.mockoapp.net"
}

host "catalog" {
name = "Catalog Service"
source = "catalog.local"
destination = "https://demo-catalog.mockoapp.net"
}

mock "GET /invoices/{id}" {
host = "billing"
format = "json"
body = <<-EOF
{ "id": {{request.params.id}}, "status": "past_due" }
EOF
}

mock "GET /products/{id}" {
host = "catalog"
format = "json"
body = <<-EOF
{ "id": {{request.params.id}}, "inStock": false }
EOF
}

Try it

Mocko routes by the Host header, which you can set by hand to test:

$curl -H 'Host: billing.local' http://localhost:8080/invoices/3
{ "id": 3, "status": "past_due" }
$curl -H 'Host: catalog.local' http://localhost:8080/categories
[ { "id": 1, "name": "Electronics" }, { "id": 2, "name": "Home" }, { "id": 3, "name": "Toys" } ]

How it works

  • Each host block matches incoming requests whose Host header equals its source.
  • Mocks with host = "billing" only answer billing traffic, so both services can mock GET /health or any overlapping route without colliding.
  • Requests on a host that no mock matches are proxied to that host's destination automatically. That is the passthrough: the categories request above never had a mock, so the real catalog backend answered. The destinations here point at live demo backends, so the whole recipe runs as-is.

Pointing your app at it

Outside of curl, the Host header comes from the URL your app resolves, so point the service hostnames at Mocko:

  • Locally, map billing.local and catalog.local to 127.0.0.1 in /etc/hosts and call http://billing.local:8080.
  • In Docker Compose, alias the Mocko container as both hostnames on the network; see Docker Compose.
  • In Kubernetes, point the services' names (or your app's service URLs) at the Mocko deployment; see Kubernetes with Helm.
destination is optional. Omit it for a service you want fully mocked: matched routes answer, and anything else on that host falls through to the instance-wide behavior described in How Matching Works.

Variations

  • Combine with the Mock One Edge Case pattern inside a host-scoped mock to break one branch of one service.
  • Hosts can also be created in the UI on a running instance, useful when the set of services changes while a staging environment is up.