Last active
April 7, 2023 10:02
-
-
Save ssd532/82ceb5d1f3295e5bf10346ee1cb90c00 to your computer and use it in GitHub Desktop.
Update the /etc/hosts file with Docker container IPs and names
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
#!/bin/bash | |
DOCKER_HOSTS_FILE="$HOME/tmp/docker-hosts" | |
HOSTS_NEW_FILE="$HOME/tmp/hosts.new" | |
# Get the list of running containers | |
CONTAINER_IDS=$(docker ps -q) | |
# Clear the current Docker hosts file | |
echo "# Docker container IPs" > $DOCKER_HOSTS_FILE | |
# Iterate through each container | |
for CONTAINER_ID in $CONTAINER_IDS; do | |
# Get the container name and IP address | |
CONTAINER_NAME=$(docker inspect -f '{{ .Name }}' $CONTAINER_ID | sed 's/^\///') | |
CONTAINER_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $CONTAINER_ID) | |
# Add an entry to the Docker hosts file | |
echo "$CONTAINER_IP $CONTAINER_NAME #DOCKER-ENTRY" >> $DOCKER_HOSTS_FILE | |
done | |
# Concatenate the Docker hosts file with the main /etc/hosts file | |
cat /etc/hosts | grep -v "#DOCKER-ENTRY" > $HOSTS_NEW_FILE | |
cat $DOCKER_HOSTS_FILE >> $HOSTS_NEW_FILE | |
# Replace the original /etc/hosts file | |
sudo mv $HOSTS_NEW_FILE /etc/hosts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment