Generating a unique hostname for Docker Swarm service containers

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.

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

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

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

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

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.

2 Likes

That’s marvellous, thanks for highlighting this

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

Did you figure it out ?