Search code examples
dockerdocker-swarm

Getting a list of services from inside a Docker container in Swarm Mode


I am trying to find a list of all running Docker Swarm Mode services that have a specific tag - but from inside a container.

I know about the hack to mount docker.sock into the container, but I'm looking for a more elegant/secure way to retrieve this information.

Essentially, I want my app to "auto-discover" other available services. Since the docker swarm manager node already has this information, this would eliminate the need for a dedicated service registry like Consul.


Solution

  • You can query docker REST API from within the container.

    For example, on MacOS, run on the host to list docker images:

    curl --unix-socket /var/run/docker.sock http:/v1.40/images/json

    To run the same inside the container, first install socat on the host.

    Then establish a relay between host's unix-socket /var/run/docker.sock and host's port 2375 using socat:

    socat TCP-LISTEN:2375,reuseaddr,fork UNIX-CONNECT:/var/run/docker.sock

    Then query host's 2375 port from within a container:

    curl http://host.docker.internal:2375/v1.40/images/json

    You should see the same result.

    Notes:

    • I don't have initialized docker swarm, so examples use docker images listing. Refer to Docker docs for listing services api.

    • You can find out API version from the output of docker info

    • Refer to What is linux equivalent of “host.docker.internal” if you don't use MacOS. Latest Linux docker versions should support host.docker.internal.