Using go templates in docker-compose.yml

docker-compose.yml:

version: "3.9"

services:
  app:
    image: nginx:latest
    hostname: "{{.Node.Hostname}}"

I’m trying to have the container hostname match the hostname of the docker host. I followed the docs Deploy services to a swarm | Docker Documentation
but it seems that the string is never evaluated and is instead passed directly.

Have you seen this post of mine, where I documented my research about placeholders: Example usage of docker swarm template placeholders

I just used them on environments, but they should also work on hostnames and with volumes declearation (not the name of the named volume itself).

Make sure you do use docker-ce from docker’s own repos! There is no guaranty other distributions or os packages act 100% like vanila docker!

My test:

me@swarm1:~$ cat <<EOF | docker stack deploy -c - test
version: "3.9"

services:
  app:
    image: nginx:latest
    hostname: "{{.Node.Hostname}}"
EOF

Then identify the node it was deployed to:

docker stack ps test

As it was on the same node I was connected to, I executed this command to verify the containers hostname:

docker exec -ti $(docker ps -aq --filter name=test) hostname

The container returned the hostname of the node as its hostname.

I was able to get it to work, I was trying to test it with compose before deploying but it didn’t seem like that was working. I just deployed it and it worked fine. interesting

I am afraid it was a wrong expectation on your side: swarm template placeholder indeed only work for swarm. docker-compose ignores/filters out all swarm specific configuration elements,