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

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: