Find docker swarm host on which a container is running by id or container hostname

When running apps on a docker swarm sometimes we know from the monitoring/alerting system just a container hostname, but measures should be taken on the host. For example, free up some disk space.

I’ve struggled to find a way to find it out in an easy way, but haven’t succeeded. So, I came up with two solutions, combined in one script:

  1. straightforward “ssh docker ps grep” which is pretty fast, at least with 3 nodes count, but requires ssh access to all docker swarm nodes via ssh to a user with permissions to docker
  2. method that leverages docker swarm manager node capabilities when the script is run on such node, but it requires three levels of calls to docker cli, each one taking some time

Concerning speed – with three nodes the first method takes less than a second, while second method takes around 25 second.

The script has comprehensive usage description and configuration capabilities through environment variables.