I have been starting to use Docker to implement a number of applications (Jira, Confluence, Jenkins, GitLab etc), but one issue I have encountered is, that unless you create specific networks for each container, on starting the container, it is given a random IP address (typically the next available one in the subnet).
Since I use reverse proxies to navigate to the containers, I need to be able to redirect from the external URL to the internal IP address of each container, but there is no simple way of identifying those IP addresses.
Enter a quick piece of code that can be used to retrieve the IP addresses for each container: dockerip.sh.
- Log into your Linux server that is running Docker as a user that can execute Docker commands.
- At the shell prompt, type ‘vi dockerip.sh’.
- In vi, press I and paste in the code on the dockerip.sh tab.
- In vi, press [ESC] and then type ‘wq dockerip.sh’ and press [ENTER].
- At the shell prompt, type ‘chmod 744 dockerip.sh’ to make the script executable.
- You can now run the script specifying each container you want the IP address for as follows:
./dockerip.sh [containername1 | containername2 | containernameN]
- If you want to display IP addresses for all Containers, simply type:
./dockerip.sh
- If you want to make life even more simple, you can create an alias for the script.
- At the shell prompt, type ‘vi ~/.bashrc’ and press [ENTER].
- In vi, type ‘dockerip=’~/dockerip.sh’.
- In vi, press [ESC] and then type ‘wq’ and press [ENTER].
- At the shell prompt, type ‘. ~/.bashrc’ to reload the file.
To run the script you can now use: dockerip in place of ./dockerip.sh.
bash$: dockerip Jira Confluence Jira: 172.18.0.2 Confluence: 172.18.0.3 bash$: dockerip Jira: 172.18.0.2 Confluence: 172.18.0.3 Jenkins: 172.17.0.2 GitLab: 172.17.0.3
# Displays the IP addresses for each Docker Container specified: # ./dockerip.sh [containername1 | containername2 | containernameN] # or all Docker Containers if no parameters are passed: # ./dockerip.sh if [ ! "$@" ] then containers="$(docker ps -f '{{.Names}}')" else containers="$@" fi for container in $containers do echo -n "$container: "; docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $container done
I’ve made a change to the dockerip script to use a more elegant way of obtaining the Docker Container names. Previously I was passing the docker ps values to sed and retreiving the names based on column positioning: I have now changed it to use a simple Go template which Docker supports natively and is inherently more reliable in retrieving the container names.