I use the following docker compose file located at /tmp/compose.yml
for docker stack deployment :
version: "3.6"
services:
service-A:
image: service-A
networks:
- net
hostname: "service-A-{{.Task.Slot}}"
deploy:
replicas: 2
service-B:
image: service-B
networks:
- net
hostname: "service-B-{{.Task.Slot}}"
deploy:
replicas: 2
networks:
net:
Run commands:
docker network create -d overlay net
docker stack deploy -c /tmp/compose.yml my
My expectation was that service-A
individual containers will be able to discover service-B
containers by container pre defined hostnames: service-B-1, service-B-2
.
However, ping service-B-1
from within any service-A
container fails.
Docs state:
hostname Sets the hostname by which the container knows itself. This is written
into /etc/hostname, into /etc/hosts as the name of the container’s
host-facing IP address, and is the name that /bin/bash inside the
container will display inside its prompt. But the hostname is not easy
to see from outside the container. It will not appear in docker ps nor
in the /etc/hosts file of any other container.
How to achieve docker swarm service container to service container communication by container pre defined hostnames?
The only way that works is adding entries like:
[service_B_container_1_virtual_ip] service-B-1
[service_B_container_2_virtual_ip] service-B-2
to /etc/hosts
of service-A
containers.