Last active
November 18, 2023 11:20
-
-
Save faiyazalam/0b6620e059175aaaa46d00891f90e96e to your computer and use it in GitHub Desktop.
Bash Script to Update /etc/hosts for Docker Containers
This file contains hidden or 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
#!/bin/bash | |
#Example Usage: bash update_hosts_for_docker_containers.sh --containers="my_container_id_1,my_container_id_2" --urls="example1.com,example2.com" | |
#Author: https://github.com/faiyazalam | |
containers="" | |
urls="" | |
# Parse arguments | |
while [[ $# -gt 0 ]]; do | |
case $1 in | |
--containers=*) | |
containers="${1#*=}" | |
shift | |
;; | |
--urls=*) | |
urls="${1#*=}" | |
shift | |
;; | |
*) | |
echo "Unknown parameter passed: $1" | |
exit 1 | |
;; | |
esac | |
done | |
# Convert comma-separated values to arrays | |
IFS=',' read -r -a containers_array <<< "$containers" | |
IFS=',' read -r -a urls_array <<< "$urls" | |
# Check if the number of containers and URLs match | |
if [ ${#containers_array[@]} -ne ${#urls_array[@]} ]; then | |
echo "The number of containers and URLs should match." | |
exit 1 | |
fi | |
# Loop through arrays to update /etc/hosts | |
for ((i=0; i<${#containers_array[@]}; i++)); do | |
ip_address=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${containers_array[i]}") | |
hostname="${urls_array[i]}" | |
# Check if the entry exists in /etc/hosts | |
if grep -q "$hostname" /etc/hosts; then | |
sudo sed -i "s/.*$hostname.*/$ip_address $hostname/" /etc/hosts | |
echo "$hostname entry updated in /etc/hosts" | |
else | |
# Add the entry to /etc/hosts | |
echo "$ip_address $hostname" | sudo tee -a /etc/hosts | |
echo "$hostname entry added to /etc/hosts" | |
fi | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Bash script facilitates the mapping of Docker container IP addresses to specific URLs in the /etc/hosts file. By providing a list of Docker container names and their corresponding URLs, this script updates the host file, ensuring the containers are accessible via their designated URLs. Usage example:
bash update_hosts_for_docker_containers.sh --containers="container1,container2" --urls="url1,url2"
.