Last active
January 12, 2022 09:49
-
-
Save bits0rcerer/fac4c01c6e0c783180c47f52ba0a975a to your computer and use it in GitHub Desktop.
Access docker container by name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# /usr/local/bin/docker-update-hosts | |
# https://stackoverflow.com/questions/37242217/access-docker-container-from-host-using-containers-name/63656003#63656003 | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /etc/systemd/system/docker-update-hosts.service | |
[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 | |
[Install] | |
WantedBy=docker.service |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to fnkr: https://stackoverflow.com/questions/37242217/access-docker-container-from-host-using-containers-name/63656003#63656003