Consul
Register services running on Docker containers
This topic provides an overview for registering services running on Docker containers in Consul.
Register a service
Start a service in a container and register it with the Consul client. The following examples refer to a counting-service
that increments a number every time it is accessed and then returns that number.
Pull the container.
$ docker pull hashicorp/counting-service:0.0.2
Run the container with port forwarding so that you can access it from your web browser by visiting http://localhost:9001.
$ docker run \
-p 9001:9001 \
-d \
--name=counting-service \
hashicorp/counting-service:0.0.2
Next, create a service definition to register the counting service with the Consul client.
/consul/config/counting.json
{
"service": {
"name": "counting",
"tags": ["go"],
"port": 9001
}
}
Create the /consul/config/counting.json
file in a container where a Consul service runs. In the following example, this container is the consul-client
container.
$ docker exec consul-client /bin/sh -c "echo '{\"service\": {\"name\": \"counting\", \"tags\": [\"go\"], \"port\": 9001}}' >> /consul/config/counting.json"
Because the Consul client does not automatically detect changes in the configuration directory, you must issue a reload command to the same container. Consul cannot register the service until you trigger a configuration reload.
$ docker exec consul-client consul reload
Configuration reload triggered
In the logs of the consul-client
container, you can find entries that confirm that the Consul client received the hangup signal, reloaded its configuration, and synced the counting service.
2022-12-15T19:02:24.945Z [INFO] agent: Synced service: service=counting