Skip to content

Instantly share code, notes, and snippets.

@rehannali
Created April 1, 2025 16:26
Show Gist options
  • Save rehannali/52c6cf0ba7376b838b77e670fcc4b483 to your computer and use it in GitHub Desktop.
Save rehannali/52c6cf0ba7376b838b77e670fcc4b483 to your computer and use it in GitHub Desktop.
This setup helps you to configure docker container IPs in host file to access later whether in local machine or remote server.

Update Docker Hosts

This utility helps you to configure docker containers IPs into host file to manage containers with hostname instead of IPs. Whther you want to access the container or redirect traffic to that container like using nginx, it worked. You don't have to configure or manually edit the host file to maintain the IPs.

Installation

Prerequisites

  • Make sure you have docker installed on your machine and it is runing.
  • Install jq utility. For example in Ubunut or debian based OS sudo apt install jq -y

Further Process

  1. Copy the content of update-docker-hosts.sh and paste it in /usr/local/bin/docker-update-hosts. If there is no file exists, ceate new file and paste the content.
  2. Set the executable permission with chmod +x /usr/local/bin/docker-update-hosts.
  3. Copy the content of docker-update-hosts.service and paste it in /etc/systemd/system/docker-update-hosts.service. If file doesn't exists, create new file and paste the content.
  4. Enable and start the service by xecuting below commands.
sudo systemctl enable docker-update-hosts.service
sudo systemctl start docker-update-hosts.service
sudo systemctl status docker-update-hosts.service

This uses builtin process by watching on docker events to modify host file and it uses jq as json parser to fetch IPs from containers.

[Unit]
Description=Update Docker containers in /etc/hosts
Requires=docker.service
After=docker.service
PartOf=docker.service
[Service]
ExecStart=/usr/local/bin/docker-update-hosts
Restart=on-failure
[Install]
WantedBy=docker.service
#!/usr/bin/env bash
set -e -u -o pipefail
hosts_file=/etc/hosts
begin_block="# BEGIN DOCKER CONTAINERS"
end_block="# END DOCKER CONTAINERS"
if ! grep -Fxq "$begin_block" "$hosts_file"; then
echo -e "\n${begin_block}\n${end_block}\n" >> "$hosts_file"
fi
(echo "| container start |" && docker events) | \
while read event; do
if [[ "$event" == *" container start "* ]] || [[ "$event" == *" network disconnect "* ]]; then
hosts_file_tmp="$(mktemp)"
docker container ls -q | xargs -r docker container inspect | \
jq -r '.[]|"\(.NetworkSettings.Networks[].IPAddress|select(length > 0) // "# no ip address:") \(.Name|sub("^/"; "")|sub("_1$"; ""))"' | \
sed -ne "/^${begin_block}$/ {p; r /dev/stdin" -e ":a; n; /^${end_block}$/ {p; b}; ba}; p" "$hosts_file" \
> "$hosts_file_tmp"
chmod 644 "$hosts_file_tmp"
mv "$hosts_file_tmp" "$hosts_file"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment