Service Discovery & Health Checks with HashiCorp Consul
In a modern microservices architecture, servers and containers come and go all the time. Auto-scaling adds new instances during traffic spikes, and crashes replace old ones with brand-new IP addresses. If your services rely on hardcoded IP addresses or manual load-balancer updates, your system will break the moment a container restarts.
HashiCorp Consul solves this problem by acting as a live, automated phonebook for your infrastructure. Services register themselves when they start, Consul continuously checks their health over HTTP or TCP, and any unhealthy node is automatically removed from DNS and HTTP lookups before users notice an outage.
- Why hardcoded IP addresses fail in dynamic cloud and Docker environments.
- How HashiCorp Consul handles dynamic service registration and active HTTP/TCP health checks.
- Hands-On Lab: How to launch a local Consul agent in Docker.
- How to register both a Node.js service and an ASP.NET Core service with
/healthendpoints. - How to stop one instance and watch Consul automatically remove the unhealthy node from DNS and HTTP lookups.
- Real-world architectural trade-offs, common pitfalls, and senior-level interview questions.
1. The Problem: Why Hardcoded IPs Break Microservices
Imagine an e-commerce platform where an Order Service needs to call a Payment Service. In a traditional setup, you might put PAYMENT_URL=http://10.0.1.25:5000 inside an environment file. That works fine on a single static server, but it falls apart in production:
- Dynamic IP addresses: When Docker, Kubernetes, or AWS ECS restarts a crashed container, it usually assigns a completely different IP address.
- Manual load-balancer updates: If you scale from 2 instances to 10 during a flash sale, someone has to update the load-balancer config—and remember to remove them later.
- Routing traffic to dead nodes: If an instance hangs or runs out of memory, a static config keeps sending requests to it, causing cascading timeouts and
502 Bad Gatewayerrors.
| Approach | How Services Find Each Other | Handling Crashed Instances |
|---|---|---|
| Hardcoded IPs / Static Config | Manual IP & port in config files | Requests fail until a human edits config and restarts |
| Traditional Load Balancer | Fixed VIP pointing to a static server pool | Requires manual pool updates when scaling |
| HashiCorp Consul | Dynamic registry queried via DNS or HTTP API | Active HTTP/TCP checks automatically drop unhealthy nodes |
2. How Consul Service Discovery & Health Checks Work
Consul combines a Service Registry with an active Health Checking Engine. Instead of waiting for a client to report a failed request, Consul proactively probes every registered service on a fixed interval (for example, every 10 seconds).
Dynamic Registration, Active Health Checks & Automatic Failover
Consul continuously polls each service's /health endpoint. When the Node.js instance stops responding, Consul marks it critical and immediately excludes it from DNS and HTTP discovery queries.
3. Hands-On Lab: Launch Consul Locally in Docker
Let's build a complete local lab. You only need Docker, Node.js (v18+), and the .NET 8 SDK installed on your machine.
First, start a local Consul agent in development mode using Docker. Dev mode runs a single-node in-memory server with the Web UI enabled, making it ideal for local testing.
Step 1: Start Consul in Docker
docker run -d --name=dev-consul \
-p 8500:8500 \
-p 8600:8600/udp \
hashicorp/consul:latest \
agent -dev -ui -client=0.0.0.0
Expected output
Unable to find image 'hashicorp/consul:latest' locally latest: Pulling from hashicorp/consul ... Status: Downloaded newer image for hashicorp/consul:latest 9f3a8c2e7b1d4a6f8c0e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a4c6e8b0d2f4a
Verify that Consul is running by opening http://localhost:8500 in your browser. You will see the Consul Web UI with a single consul service listed.
host.docker.internal. On Linux, pass --add-host=host.docker.internal:host-gateway to the docker run command.4. Register a Node.js Service with /health Checks
Now let's create a lightweight Node.js service using Express. When it starts up, it will call Consul's HTTP API (/v1/agent/service/register) to register itself under the service name orders-api along with an active HTTP health check.
Step 2: Initialize the Node.js project
mkdir node-consul-demo && cd node-consul-demo
npm init -y
npm install express
File: index.js
const express = require("express");
const app = express();
const PORT = 4001;
const SERVICE_ID = "orders-node-1";
const SERVICE_NAME = "orders-api";
const CONSUL_URL = "http://localhost:8500";
// 1. Active HTTP Health Check endpoint
app.get("/health", (req, res) => {
res.status(200).json({ status: "healthy", runtime: "Node.js" });
});
// 2. Sample business endpoint
app.get("/orders", (req, res) => {
res.json({ service: SERVICE_ID, orders: ["ORD-101", "ORD-102"] });
});
// 3. Register service with Consul on startup
async function registerWithConsul() {
const registration = {
ID: SERVICE_ID,
Name: SERVICE_NAME,
Address: "host.docker.internal",
Port: PORT,
Tags: ["nodejs", "v1"],
Check: {
HTTP: `http://host.docker.internal:${PORT}/health`,
Interval: "5s",
Timeout: "2s",
DeregisterCriticalServiceAfter: "1m"
}
};
const res = await fetch(`${CONSUL_URL}/v1/agent/service/register`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(registration)
});
if (!res.ok) {
throw new Error(`Consul registration failed: ${res.status}`);
}
console.log(`Registered ${SERVICE_ID} with Consul.`);
}
app.listen(PORT, async () => {
console.log(`Node.js service running on http://localhost:${PORT}`);
try {
await registerWithConsul();
} catch (err) {
console.error(err.message);
}
});
Run the Node.js service in a terminal:
node index.js
Expected output
Node.js service running on http://localhost:4001 Registered orders-node-1 with Consul.
5. Register an ASP.NET Core Service with /health Checks
Next, let's register a second instance of the same logical service (orders-api), this time written in ASP.NET Core. Using two different runtimes shows that Consul is completely language-agnostic.
Step 3: Create the ASP.NET Core Minimal API
dotnet new web -n DotNetConsulDemo
cd DotNetConsulDemo
File: Program.cs
using System.Text;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();
var app = builder.Build();
const int port = 5001;
const string serviceId = "orders-dotnet-1";
const string serviceName = "orders-api";
const string consulUrl = "http://localhost:8500";
// 1. Built-in ASP.NET Core /health endpoint
app.MapHealthChecks("/health");
// 2. Sample business endpoint
app.MapGet("/orders", () => Results.Ok(new
{
service = serviceId,
orders = new[] { "ORD-201", "ORD-202" }
}));
// 3. Register with Consul when the app starts
app.Lifetime.ApplicationStarted.Register(() =>
{
Task.Run(async () =>
{
using var http = new HttpClient();
var payload = new
{
ID = serviceId,
Name = serviceName,
Address = "host.docker.internal",
Port = port,
Tags = new[] { "dotnet", "v1" },
Check = new
{
HTTP = $"http://host.docker.internal:{port}/health",
Interval = "5s",
Timeout = "2s",
DeregisterCriticalServiceAfter = "1m"
}
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await http.PutAsync($"{consulUrl}/v1/agent/service/register", content);
if (response.IsSuccessStatusCode)
Console.WriteLine($"Registered {serviceId} with Consul.");
else
Console.WriteLine($"Consul registration failed: {response.StatusCode}");
});
});
app.Run($"http://0.0.0.0:{port}");
Run the ASP.NET Core service in a second terminal:
dotnet run
Expected output
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://0.0.0.0:5001
Registered orders-dotnet-1 with Consul.
6. Observe Automatic Failover in HTTP & DNS Lookups
Both services are now registered under orders-api and passing their /health checks every 5 seconds. Let's query Consul to see both healthy instances.
Step 4: Query healthy instances via HTTP API
curl -s "http://localhost:8500/v1/health/service/orders-api?passing=true" | jq '.[].Service | {ID, Address, Port}'
Expected output (Both instances healthy)
{
"ID": "orders-dotnet-1",
"Address": "host.docker.internal",
"Port": 5001
}
{
"ID": "orders-node-1",
"Address": "host.docker.internal",
"Port": 4001
}
Step 5: Query healthy instances via Consul DNS
Consul also exposes a built-in DNS server on port 8600. You can run an SRV lookup to get both the host and port of every healthy instance:
dig @127.0.0.1 -p 8600 orders-api.service.consul SRV +short
Expected output
1 1 5001 host.docker.internal. 1 1 4001 host.docker.internal.
Step 6: Stop the Node.js instance and watch Consul react
node index.js and press Ctrl + C to simulate a sudden crash.
curl -s "http://localhost:8500/v1/health/service/orders-api?passing=true" | jq '.[].Service | {ID, Address, Port}'
Expected output (Unhealthy node automatically removed)
{
"ID": "orders-dotnet-1",
"Address": "host.docker.internal",
"Port": 5001
}
Consul immediately excluded orders-node-1 from both the HTTP ?passing=true endpoint and the DNS SRV response. Because we set DeregisterCriticalServiceAfter: "1m", Consul will also permanently clean up the dead registration after 1 minute.
7. Architecture & Real-World Trade-offs
Running Consul in a local Docker container is straightforward, but production distributed systems introduce important architectural trade-offs:
- Client-Side vs. Server-Side Discovery: With client-side discovery, your calling service queries Consul directly and picks an instance (giving you lower latency and no extra hop, but coupling your app to Consul). With server-side discovery, a reverse proxy like NGINX, Traefik, or Envoy watches Consul and routes traffic for you.
- Active Health Check Overhead: Polling
/healthevery 1 second across 500 microservices creates unnecessary CPU and network load. Keep health check endpoints lightweight (avoid running heavy SQL queries inside/health) and use a balanced interval like10sto15s. - TCP vs. HTTP Health Checks: A TCP check only confirms that a port is open—it cannot tell if your app is deadlocked or returning
500 Internal Server Error. Prefer HTTP/healthchecks for web APIs, and reserve TCP checks for databases, caches, or non-HTTP brokers. - High Availability (Raft Consensus): Never run a single Consul server in production. Deploy 3 or 5 Consul server nodes across different AWS Availability Zones so the cluster can survive node failures using the Raft consensus protocol.
0s by default—make sure your client respects it or use Consul's HTTP API with blocking queries.8. Hands-On Practice
Modify the Node.js registration payload to use a TCP check instead of an HTTP check.
Hint: Replace HTTP: "http://..." with TCP: "host.docker.internal:4001" inside the Check object.
Update both the Node.js and ASP.NET Core services so they call PUT /v1/agent/service/deregister/{SERVICE_ID} when shutting down cleanly.
Expected result: The service disappears from the Consul UI instantly on Ctrl + C instead of waiting for the next failed health check.
Query Consul's HTTP API to return only healthy orders-api instances that have the dotnet tag.
Hint: Add &tag=dotnet to the /v1/health/service/orders-api?passing=true URL.
9. Interview Questions
Answer: A liveness check tells you if the process is running and not deadlocked. A readiness check tells you if the service is actually ready to accept traffic (for example, its database connection pool is warmed up). Consul's health checks act like readiness checks—failing them removes the node from traffic without necessarily restarting the container.
Answer: Consul uses the Gossip protocol (Serf) for decentralized membership and fast failure detection across thousands of client agents. It uses Raft consensus strictly among the small cluster of Consul servers (3 or 5 nodes) to maintain a strongly consistent service catalog and key-value store.
?passing=true when querying Consul's HTTP API?
Answer: Without ?passing=true, the /v1/health/service/:name endpoint returns all registered instances—including ones in warning or critical states. Always pass ?passing=true when resolving endpoints for live traffic.
Answer: Use SuccessBeforePassing and FailuresBeforeCritical in Consul's health check configuration so a flapping service must pass multiple consecutive checks before receiving traffic, and combine it with client-side exponential backoff.
Conclusion
Dynamic service discovery with HashiCorp Consul eliminates one of the biggest operational bottlenecks in microservices: managing IP addresses and load balancers by hand. By pairing automatic registration with active HTTP and TCP health checks, your system heals itself when instances crash or scale.
Try extending this lab by running multiple instances of both services behind a reverse proxy, or share your own Consul architecture patterns on Upgradix by Shrash Studio to help the developer community level up.
Official Documentation
- HashiCorp Consul Documentation – Service Discovery
- HashiCorp Consul Documentation – Define Health Checks
- HashiCorp Consul API Reference – Agent Service Endpoints
Upgradix by Shrash Studio – Learn Technology. Build Your Future.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.