Docker Community Forums

Share and learn in the Docker community.

Generating a unique hostname for Docker Swarm service containers

(Justin Heyes-Jones) #1

I run a number of services, each having a role, for example: frontend, backend

When the services report statsD and logging data etc they report the hostname as the container ID. It would be great if I could see the docker role at that point.

I would like to change the hostname on the containers to have the role name. I can do this by adding the --hostname parameter to docker service create

–hostname frontend

Whilst this works, there is now no way to match the servers to container IDs.

Is there a way to have a hostname generated that prefixes or appends the container ID so that I get the best of both worlds?

Since it’s not easy or recommended to try to modify the docker container during its startup script, this would have to be a Docker Swarm feature.

(Eldeberde) #2

Hello, you can run a command in your entrypoint script adding to the /etc/hostname your words.

sed -i ‘1s/^/frontend/’ /etc/hostname

(Justin Heyes-Jones) #3

I was hoping to do something like that but I get an error:

sed: can’t move ‘/etc/hostnameeBHDAe’ to ‘/etc/hostname’: Resource busy

(King Chung Huang) #4

You can use Go templates for the hostname. For example, you could do --hostname="frontend-{{.Node.Hostname}}-{{.Task.ID}}" to append the swarm node’s host name and the service task’s ID.

See Create services using templates.

(Justin Heyes-Jones) #5

That’s marvellous, thanks for highlighting this

(Justin Heyes-Jones) #6

I ran into a problem trying to make this work. What I wanted was to keep the existing hostname (which defaults to the container ID) and add the service name. Unfortunately there doesn’t seem to be a template that represents the container ID