How to connect to a specific task in a docker swarm service?

Hey,

I have some problems with my Docker Swarm setup. I’ve created a docker service with a certain amount of replicas. The service itself is part of an overlay network which includes other services as well. Now I have to access a specific task (replica) of a docker service in the network.

I know that you can access a service pretty easily by just using the name of the service and the connection will than be loadbalanced. But I have to directly access a certain task. Is there something similar for that?

Thanks in advance!

This question only makes sense in a situation where a container should communicate with a specific task container in the same network. So I assume you are not asking about outside to specific container task communication.

By default, swarm services register a ipvs ip, which load balances automatically to the tasks. Whenever you use a service name inside a container network, the ip of the ipvs will be used.

You can bypass the ipvs loadbalancer, by using tasks.{servicename} (of course {servicename} needs to be replaced with the real service name}.

Though, you could try if you can leverage template placeholders for this:

---
version: '3.8'
services:
  myservice:
    hostname: 'myservice-{{.Task.Slot}}'
   ....

I am not sure if template placeholders can be used for hostname (they are not available for every configuration element), but it’s worth trying.
If it does, you should be able to access a specific task by its predictable hostname from a container in the same container network.

If you are curious about template placeholders:

Thanks for this, I can confirm using template placeholders in the hostname works for this. And the hostname doesn’t resolve from another container until the templated service is healthy, which is nice.