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 specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedInRelated Article - Docker Compose
- Difference Between Stop, Down, Up, and Start in Docker Compose
- How to Add a Network Mode in Docker Compose
- How to Recreate Containers From New Images Using Docker-Compose
- Difference Between Docker and Docker Compose
- How to View Specific Docker Compose Service Logs
- How to Update Existing Images With Docker Compose