10

I'm unable to get the Docker Compose hostname command to work.

I'm running a simple docker-compose.yml:

version: '3'
services:
  redis1:
    image: "redis:alpine"
    hostname: redis1host
  redis2:
    image: "redis:alpine"
    hostname: redis2host

Once I run this with docker-compose up, I should be able to run docker-compose exec redis1 /bin/ash and then ping redis2host to talk to the other Redis container, but the ping just doesn't reach its destination. I can ping the other Redis container with ping redis2.

ping redishost2 should work, no?

1 Answer 1

25

The hostname directive simply sets the hostname inside the container (that is, the name you get back in response to the hostname or uname -n commands). It does not result in a DNS alias for the service. For that, you want the aliases directive. Since that directive is per-network, you need to be explicit about networks rather than using the compose default, for example:

version: '3'
services:
  redis1:
    image: "redis:alpine"
    hostname: redis1host
    networks:
      redis:
        aliases:
          - redis1host
  redis2:
    image: "redis:alpine"
    hostname: redis2host
    networks:
      redis:
        aliases:
          - redis2host

networks:
  redis:
Sign up to request clarification or add additional context in comments.

1 Comment

If you don't want to add use network in your docker-compose, just using networks: default aliases ... would also works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.