In this article, I explain how to get the IP address of a Docker container, and even some ways you can automate it.
Getting the IP address of a Docker container surprisingly isn't the most straight forward thing. It's really not too bad, though.
There's a few different ways you can go about it, but today I'm going to cover the docker inspect
approach.
Here's a bash script I wrote for getting the IP address of a Docker container and displaying it:
#!/bin/bash
echo "Please enter the docker container name: "
read name
docker inspect $(docker ps -q -f name=$name) | grep '"IPAddress": ' | tail -n1 | cut -f 2 -d ':' | tr '"' ' ' | tr ',' ' ' | xargs
Basically, this scripts transforms "IPAddress": "172.17.0.3", to 172.17.0.3 and displays it.
Here's an example of the output of the script:
As you can see, it displays only the IP address of the Docker container. This can actually be quite useful and can even be used to automate things (like if we need to store only the IP address somewhere or use the IP address for something like ping or traceroute), we can accomplish this if we modify the script slightly to accept a parameter, for example like so:
#!/bin/bash
docker inspect $(docker ps -q -f name=$1) | grep '"IPAddress": ' | tail -n1 | cut -f 2 -d ':' | tr '"' ' ' | tr ',' ' ' | xargs
where $1
would be the name of the Docker container that we call the script with, like so: ./get-docker-container-ip.sh lamp
. Of course, it doesn't have to be a script, it's also possible to turn it into a command that we could use in bash (or zsh or whatever your shell of choice may be) to easily find the IP address of any Docker container we may have running.
In zsh file .zshrc
, this would look like:
function getdockerip() {
docker inspect $(docker ps -q -f name=$1) | grep '"IPAddress": ' | tail -n1 | cut -f 2 -d ':' | tr '"' ' ' | tr ',' ' ' | xargs;
}
You could then call it in zsh like so: getdockerip lamp
which would then display the IP address 172.17.0.3
Hopefully this article was helpful, and you can now see various ways in which we can get a Docker container IP address using the docker inspect
command.