Docker compose is a multi-container managing tool that is frequently utilized to configure the services for multi-container applications. While creating containers in Docker, the container id will be set as the default hostname of a container. However, users can manually set and overwrite the container hostname. The containers generated by the “docker run” command can easily set the hostname through the “-h” or “–hostname” command. However, in Docker compose, users can set the hostname in the “docker-compose.yml” file.
This write-up will provide the method to set the hostname in Docker compose.
How to Set the Hostname in Docker Compose?
To set the hostname in Docker compose, you can utilize the “hostname” key or set the “HOSTNAME” environment variable in the “docker-compose.yml” file.
To set the hostname in the compose file, follow the provided steps.
Step 1: Set Hostname in “docker-compose.yml” File
First, create a “docker-compose.yml” file and paste the provided instructions into compose file. Here, we have utilized the “hostname” key to set the hostname for the container:
services:
web:
build: .
hostname: golang.example.com
ports:
- "8080:8080"
golang:
image: "golang:alpine"
For instance, we have set “golang.example.com” as the hostname of the container:
Alternatively, users can use the environment variable “HOSTNAME” to set the container’s hostname as shown below:
- HOSTNAME=golang.example.com
Step 2: Start and Create the Container
In the next step, create and start the container with the help of the “docker-compose up” command:
For confirmation, go to the “Docker Desktop” application and check the container’s menu. Here, you can see that the “golangapp” container is running one service out of two. Visit the “golangapp” container:
Step 3: Inspect the Container
Then, inspect the container that executes the web service:
From the “Inspect” menu, you can see that we have successfully set the hostname in Docker compose:
Alternatively, users can use the “docker inspect <containerID/container-Name>” command to inspect the container:
It can be observed that the environment variable “HOSTNAME” has been configured for the container:
That’s all! We have provided the method to set the hostname in Docker compose.
Conclusion
To set the hostname in Docker compose, you can use the “hostname” key or set the environment variable “HOSTNAME”. For this purpose, first, create a “docker-compose.yml” file and use the “hostname: <host-name>” statement in the file. To set the hostname using the environment variable, utilize the “environment: – HOSTNAME=<host-name>” statement. This write-up has provided the method to set the hostname in Docker compose.