How to Add a Hostname to a Service in Docker-Compose

How to Add a Hostname to a Service in Docker-Compose

Each container for service in Docker joins the default network. It is reachable by other containers on that network and discoverable by them at a hostname identical to the container name.

This article will discuss adding hostnames to our container service in docker-compose.

Add a Hostname to a Service in Docker-Compose

As docker-compose version 3.0, we can use the hostname key and add it to our YAML file. Ensure that we have clearly defined the version of what docker-compose uses when running our services.

To determine the version, use the version key with the value of 3 or 3.0.

version: "3.0"
services:
    sampleservice:
        hostname: service-hostname

Without the version key, docker-compose will use the default value of version 1 when running the service. With version 1, we will not set up our hostname correctly.

However, there is a known issue where the hostname will not be visible to other containers if we execute the docker run command. We can define an alias instead and assign the container a name as a workaround.

To define an alias, enable defined aliases first by running the command below.

docker-compose run --use-aliases

After running, we can use the aliases key and include it in our YAML file.

version: "3.0"
services:
    sampleservice:
        networks:
            samplenetwork:
                aliases:
                    - alias1
                    - alias2

After which, manually assign the alias to the service with the following command.

docker-compose run --name alias1 sampleservice
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - Docker Compose