dockerdocker-composedocker-swarm

Docker-compose: setting hostname equal to its hostname of where the container is running


Right now, I have two-node in swarm cluster

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
yey1njv9uz8adf33m7oz0h80f *   redis2              Ready               Active              Leader
lbo91v2l15h24isfd5jegoxu1     redis3              Ready               Active   

this is docker-compose.yml file

version: "3"
services:
  daggr:
    # replace username/repo:tag with your name and image details
    image: daggr
    hostname: examplehostname
    deploy:
      replicas: 1
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
      restart_policy:
        condition: on-failure
    ports:
      - "4000:80"
    networks:
      - webnet
  visualizer:
    image: dockersamples/visualizer:stable
    ports:
        - "8080:8080"
    volumes:
        - "/var/run/docker.sock:/var/run/docker.sock"
    deploy:
        placement:
            constraints: [node.role == manager]
    networks:
        - webnet
  redis:
    image: redis
    networks:
        - webnet
networks:
  webnet:

as you see, i am explictly setting hostname for daggr service

daggr container basically runs a python tornado web server

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('Hello from daggr running on %s\n' % socket.gethostname())

I've tested out as below

$ curl redis2:4000
Hello from daggr running on examplehostname

Now, instead of statically setting the hostname, i want it to be dynamic matching to hostname of where the container is running. ie. if daggr container is running on redis2 it should say redis2 and on redis3, it should say redis3.

How can i specify that from docker-compose.yml file?


Solution

  • If you are running at least Docker 17.10 then you can use something like this:

    services:
      daggr:
        hostname: '{{.Node.Hostname}}'
    

    See this for more information.