Docker How To Set Hostname
We are going to show you how to set the hostname in for a Docker container. This is easy but you need to know how it is meant to work and what to expect.
NOTE:
- Don’t edit /etc/hostname as this will be overridden by docker.
- You aren’t meant to set the hostname at build time or in the image either. Its meant to be set dynamically at the time of container deployment.
Set Hostname when Deploying Container
Specify the hostname:
docker run -h crusty -i -t ubuntu bash
Specify the FQDN for the container:
docker run -h crusty.crab.com -i -t ubuntu bash
Verify the hostname:
hostname
How to Set Hostname with Docker Compose
You can specify the hostname inside a docker compose file like this:
vi docker-compose.yamlservices: web: image: nginx hostname: crusty.crab.com ports: - "8080:8080"
Bring it up:
docker compose up
Attach to the container:
docker exec -it test1-web-1 bash
Verify the hostname:
hostname