Access docker application by hostname
To access a docker application by a particular hostname, the file: /var/lib/docker/containers/CONTAINER_ID/config.json
requires the change of the Hostname and Domainname "Config":{"Hostname":"www","Domainname":"example.local", ...}
. This way, the container will have all the necesarry information.
An elegant way, instead of directly editing the configuration file, is to use docker-compose (aka fig) to run the application:
...
web:
image: example/application
hostname: www
domainname: example.local
ports:
- "80:80"
volumes:
- /var/www
...
The next little script will search all active containers, get that necessary info for the /etc/hosts
file and adjust it with the required names:
#!/bin/bash
FILE=/etc/hosts
DEFAULT_DOMAIN='example.local'
for CID in $(docker ps --filter="name=$name" -q); do
IP=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${CID})
HOSTNAME=$(docker inspect --format '{{ .Config.Hostname }}' ${CID})
DOMAINNAME=$(docker inspect --format '{{ .Config.Domainname }}' ${CID})
if [ -n "$HOSTNAME" ] && [ -n "$DOMAINNAME" ]; then
HOST="$HOSTNAME.$DOMAINNAME"
else
HOST="$CID.$DEFAULT_DOMAIN"
fi
sed -i "/\b$IP\b/d" $FILE
if grep -q $HOST "$FILE"; then
sed -i "/$HOST/ s/.*/$IP\t$HOST/g"
else
echo -e "\n$IP $HOST" >> $FILE
fi
done
After running the script, the application should be available now at: http://www.example.local
.
UPDATED:
Another way is to add a bridge network on the host, giving a static IP address such as 192.168.33.100.
After that the docker port forwarding which accept IP address as well should be use. In docker compose yaml the syntax is:
...
ports:
- "192.168.33.100:80:80"
...
The file /etc/hosts
needs to be updated with the IP pointing to www.example.local
. This way can be added as many bridges having different static IPs with only only modification of the /etc/hosts file per docker/docker-compose project.