Docker multiple ipaddress - docker

I have couple of containers running
vagrant#nav:~$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3401574617ea j/ros-tutorials:latest "/tini -- /ros_ent..." About an hour ago Up About an hour rosdemo_master.1.yled0m2ygtoha1gs09mrvwho5
dd1a5a4ed5b2 j/ros-tutorials:latest "/tini -- /ros_ent..." About an hour ago Up About an hour rosdemo_listener.1.fjv2u7yxihxvzkfzmomhnq9
but when I try to get their ipaddress using the below script -
for i in $(sudo docker ps -q); do sudo docker inspect $i| grep IPA; done
I get the following output -
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAMConfig": {
"IPAddress": "10.255.0.5",
"IPAMConfig": {
"IPAddress": "10.2.0.7",
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAMConfig": {
"IPAddress": "10.2.0.9",
wondering why I get 3 ipaddresses -
10.255.0.5
10.2.0.7
10.2.0.9

The containers are attached to multiple Docker networks.
Don't use grep to extract the IP Addresses, This is all structured data and Docker supports go template formatting out of the box.
To get the main IP Address:
docker inspect $CID \
-f '{{ .NetworkSettings.IPAddress }}'
The get any IP Addresses assigned to networks:
docker inspect $CID \
-f '{{ range .NetworkSettings.Networks }}{{ .IPAddress }}{{ end }}'
To print the network name along with the IP:
docker inspect $CID \
-f '{{ range $k,$v :=.NetworkSettings.Networks }}{{$k}} {{.IPAddress}}{{ end }}'

Related

How to get all ip addresses on a docker network?

I have containers running in a swarm stack of services (on different docker-machines each) connected together on an overlay docker network.
How would it be possible to get all used ip adresses on the network associated with their services or container name from inside a container on this network?
Thank you
If you want to execute this command from inside containers, first you have to mount docker.sock for each service (assuming that docker is installed in the container)
volumes:
- /var/run/docker.sock:/var/run/docker.sock
then in each container you have to install jq and after that you can simply run docker network inspect <network_name_here> | jq -r 'map(.Containers[].IPv4Address) []' expected output something like:
172.21.0.2/16
172.21.0.5/16
172.21.0.4/16
172.21.0.3/16
Find the name OR ID of overlay network -
$ docker network ls | grep overlay
Do a inspect -
docker inspect $NETWORK_NAME
You will be able to find the container names & IPs allocated to them. You can do a fetch/grep the required values from the inspect output. You will find the output something as below -
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.23.0.0/16",
"Gateway": "172.23.0.1"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"183584efd63af145490a9afb61eac5db994391ae94467b32086f1ece84ec0114": {
"Name": "emailparser_lr_1",
"EndpointID": "0a9d0958caf0fa454eb7dbe1568105bfaf1813471d466e10030db3f025121dd7",
"MacAddress": "02:42:ac:17:00:04",
"IPv4Address": "172.23.0.4/16",
"IPv6Address": ""
},
"576cb03e753a987eb3f51a36d4113ffb60432937a2313873b8608c51006ae832": {
"Name": "emailparser",
"EndpointID": "833b5c940d547437c4c3e81493b8742b76a3b8644be86af92e5cdf90a7bb23bd",
"MacAddress": "02:42:ac:17:00:02",
"IPv4Address": "172.23.0.2/16",
"IPv6Address": ""
},
Assuming you're using the default VIP endpoint, you can use DNS to resolve the IP's of a service. Here's an example of using dig to get VIP IP using and then get the individual container IP's behind that VIP using tasks.
docker network create --driver overlay --attachable sweet
docker service create --name nginx --replicas=5 --network sweet nginx
docker container run --network sweet -it bretfisher/netshoot dig nginx
~~~
;; ANSWER SECTION:
nginx. 600 IN A 10.0.0.3
~~~
docker container run --network sweet -it bretfisher/netshoot dig tasks.nginx
~~~
;; ANSWER SECTION:
tasks.nginx. 600 IN A 10.0.0.5
tasks.nginx. 600 IN A 10.0.0.8
tasks.nginx. 600 IN A 10.0.0.7
tasks.nginx. 600 IN A 10.0.0.6
tasks.nginx. 600 IN A 10.0.0.4
~~~
for n in `docker network ls | awk '!/NETWORK/ {print $1}'`; do docker network inspect $n; done
First, find the name of the network which your swarm is using.
Then run docker network inspect <NETWORK-NAME>. This will give you a JSON output, in which you'll find an object with key "Containers". This object reveals all the containers in the network and their IP addresses respectively.

How do I list all containers in a user-defined docker network?

How do I get a list of all the containers in a user-defined docker network?
I would like to get all the commit hashes of every container for a specific user-defined docker network.
docker network inspect \
-f '{{ range $key, $value := .Containers }}{{ printf "%s\n" $key}}{{ end }}' \
<network-id>
will give a newline delimited list of the container hashes belonging to the network-id network.
You can adjust the printf format to get other syntax (comma-separated, tab-separated, container id+name, etc). For example:
$ docker network inspect \
-f '{{ range $key, $value := .Containers }}{{printf "%s: %s\n" $key .Name}}{{ end }}' \
web-ingress
0b7f82ad7535ac7c1a454aaf0a5df6b87547d3cb9d751d0e0e1b4952a849b11b: mon_grafana.1.v5i0ea6nv12k0h3eo8egglg6n
1cce723642af2ce9382c7d46cca868d4674b4645d07458eeed9e928d29a4fb1f: mon_prometheus.1.lsfdcig6uhqfbbv7n07irpj3j
1f4840710f77fa1e02bd3e95581139b9f3c13fe4c857ce6ac44bfbdae4916920: mon_alertmanager.1.kwvw7kqsfpi9qzpmqdrd85yc7
2efea443fee41fd5dbca714145ca6ff95d91be9c60a469be597aadfaca90914d: mon_unsee.1.3lg8qgnvshibklnypzt5rw95s
6fdb893488f6e56766501e763d4c60196ae12a22ee9bd204d84fe324331714e8: mon_dashboard.1.r6b6nhatwmk88y5ncgagnaxh4
lb-web-ingress: web-ingress-endpoint
You can list all networks with:
docker network ls
And inspect one network to see its hosts (containers)
docker network inspect <network-id>
Inspecting that a container, you can see which network it is connected to:
docker inspect <container-id>
More info in the docs: https://docs.docker.com/engine/userguide/networking/work-with-networks/#create-networks
Another way using pure bash and no python - easier to remember for me
docker network inspect YOUR_NETWORK_ID | grep Name | tail -n +2 | cut -d':' -f2 | tr -d ',"'
Sample output
container1
container2
A simple command to list the names of the container using a custom network is:
docker inspect network-name | grep Name
This command will list the name of the network and containers connected to it like below:
"Name": "network-name",
"Name": "Container1",
"Name": "Container2",
Solution can be simple as below as well. To list name of the container only
docker network inspect NETWORK ID | grep "Name" | awk -F":" '{print $2}' | tr -d ',"'
This is my bash command using python's json parsing
docker network inspect YOUR_NETWORK_ID \
| python -c "import sys, json; print([v['Name'] for k,v in json.load(sys.stdin)[0]['Containers'].items()])"
Sample output
[u'container1', u'container2']
I found that when a container has been brought up with an attribute of
network_mode: "service: <some service name>"
that the 'docker inspect' or 'docker network inspect ' commands are not going to give you the information as detailed above.
What you will see instead is something like this:
"NetworkMode": "container: <some container id representing the service>"
Allow me to contribute with another way of obtaining the result, still using docker network inspect, but providing other possibilities in terms of data inspection and output format.
You list the available networks for Docker:
$ docker network ls
NETWORK ID NAME DRIVER SCOPE
a1682358dfa3 bridge bridge local
c6910d1da750 host host local
c9790e542025 none null local
9b265ecb4042 web_default bridge local
You inspect the network, with output in JSON, accessing the Containers object + prettifying the JSON:
$ docker network inspect web_default -f '{{json .Containers}}' | python3 -m json.tool
{
"5d05c2606b022b0c9bc480f138b8f8f0e382dca4b1decb1c27181a66e641803f": {
"Name": "django",
"EndpointID": "b6bf6b1dc5437f2359fb550368a5bc6529cd80fa5b9ece3c752eecef6627ea57",
"MacAddress": "02:42:ac:12:00:03",
"IPv4Address": "172.18.0.3/16",
"IPv6Address": ""
},
"b971715bd0b3560831b03e86bcf2151ed04a60a46ad90b24f1f2265617360344": {
"Name": "postgres",
"EndpointID": "5883f465e235c66327271c1dfd05372f02012efa78928dd447c5444b0468647c",
"MacAddress": "02:42:ac:12:00:02",
"IPv4Address": "172.18.0.2/16",
"IPv6Address": ""
}
}
You can even redirect the command output to a for further inspection:
$ docker network inspect web_default -f '{{json .Containers}}' | python3 -m json.tool > web_default_containers.json

docker healthcheck in config.v2.json

docker ps --quiet | xargs docker inspect --format '{{ .Id }}: Health={{ .State.Health.Status }}'
c1ab47fdc94858275e9327ce56d039010cb9db1eb7865e0917f3d8a74862367e: Health=unhealthy
**Template parsing error: template: :1:27: executing "" at <.State.Health.Status>: map has no entry for key "Health"**
I just want to know why the error map has no entry for key "Health is reported after docker inspect command. The status should be in the container's config.v2.json file, however, in that file, there's no unhealthy under Status, so I want to know where is the "Health=unhealthy" come from.
Thanks.
The ouput of command docker inspect, it shows the json as response.
If you notice the response, there is nothing called Health. Hence, the error. However, there is State -> Status whose value is running. So just use .State.Status instead of .State.Health.Status
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 23570,
"ExitCode": 0,
"Error": "",
"StartedAt": "2016-10-30T07:06:14.114090476Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
Since you wanted to see Status, please use below command which shows as you desired output:
sudo docker ps --quiet | xargs sudo docker inspect --format '{{ .Id }}:Health={{ .State.Status }}'
5db8668eb121bd67b6fdeba12269fa7f194c48140b5d547c70befe70b2c3f607:Health=running
To show different Status value for another container which is not running any more shows as below :
$ sudo docker inspect --format '{{ .Id }}:Health={{ .State.Status }}' 060d98f7838e
060d98f7838ec901fd7d3c855254af0d15702d2758d61f6754af8899bee9613a:Health=exited
Hope this is helpful.

docker 1.12 swarm mode: how to connect to another container on overlay network and how to use loadbalance?

I used docker-machine on mac os. and create the swarm mode cluster like:
➜ docker-machine create --driver virtualbox docker1
➜ docker-machine create --driver virtualbox docker2
➜ docker-machine create --driver virtualbox docker3
➜ config docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
docker1 - virtualbox Running tcp://192.168.99.100:2376 v1.12.0-rc4
docker2 - virtualbox Running tcp://192.168.99.101:2376 v1.12.0-rc4
docker3 - virtualbox Running tcp://192.168.99.102:2376 v1.12.0-rc4
➜ config docker-machine ssh docker1
docker#docker1:~$ docker swarm init
No --secret provided. Generated random secret:
b0wcyub7lbp8574mk1oknvavq
Swarm initialized: current node (8txt830ivgrxxngddtx7k4xe4) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join --secret b0wcyub7lbp8574mk1oknvavq \
--ca-hash sha256:e06f5213f5c67a708b2fa5b819f441fce8006df41d588ad7823e5d0d94f15f02 \
10.0.2.15:2377
# on host docker2 and host docker3, I run cammand to join the cluster:
docker#docker2:~$ docker swarm join --secret b0wcyub7lbp8574mk1oknvavq --ca-hash sha256:e06f5213f5c67a708b2fa5b819f441fce8006df41d588ad7823e5d0d94f15f02 192.1
68.99.100:2377
This node joined a Swarm as a worker.
docker#docker3:~$ docker swarm join --secret b0wcyub7lbp8574mk1oknvavq --ca-hash sha256:e06f5213f5c67a708b2fa5b819f441fce8006df41d588ad7823e5d0d94f15f02 192.1
68.99.100:2377
This node joined a Swarm as a worker.
# on docker1:
docker#docker1:~$ docker node ls
ID HOSTNAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS
8txt830ivgrxxngddtx7k4xe4 * docker1 Accepted Ready Active Leader
9fliuzb9zl5jcqzqucy9wfl4y docker2 Accepted Ready Active
c4x8rbnferjvr33ff8gh4c6cr docker3 Accepted Ready Active
then I create the network mynet with overlay driver on docker1.
The first question: but I cann`t see the network on other docker hosts:
docker#docker1:~$ docker network create --driver overlay mynet
a1v8i656el5d3r45k985cn44e
docker#docker1:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
5ec55ffde8e4 bridge bridge local
83967a11e3dd docker_gwbridge bridge local
7f856c9040b3 host host local
bpoqtk71o6qo ingress overlay swarm
a1v8i656el5d mynet overlay swarm
829a614aa278 none null local
docker#docker2:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
da07b3913bd4 bridge bridge local
7a2e627634b9 docker_gwbridge bridge local
e8971c2b5b21 host host local
bpoqtk71o6qo ingress overlay swarm
c37de5447a14 none null local
docker#docker3:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
06eb8f0bad11 bridge bridge local
fb5e3bcae41c docker_gwbridge bridge local
e167d97cd07f host host local
bpoqtk71o6qo ingress overlay swarm
6540ece8e146 none null local
the I create the nginx service which echo the default hostname on index page on docker1:
docker#docker1:~$ docker service create --name nginx --network mynet --replicas 1 -p 80:80 dhub.yunpro.cn/shenshouer/nginx:hostname
9d7xxa8ukzo7209r30f0rmcut
docker#docker1:~$ docker service tasks nginx
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
0dvgh9xfwz7301jmsh8yc5zpe nginx.1 nginx dhub.yunpro.cn/shenshouer/nginx:hostname Running 12 seconds ago Running docker3
The second question: I cann`t access from the IP of docker1 host to the service. I only get the response to access the IP of docker3 .
➜ tools curl 192.168.99.100
curl: (52) Empty reply from server
➜ tools curl 192.168.99.102
fda9fb58f9d4
So I think there have no loadbalance. How do I to use the build-in loadbalance ?
Then I create another service on the same network with busybox image to test ping :
docker#docker1:~$ docker service create --name busybox --network mynet --replicas 1 busybox sleep 3000
akxvabx66ebjlak77zj6x1w4h
docker#docker1:~$ docker service tasks busybox
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
9yc3svckv98xtmv1d0tvoxbeu busybox.1 busybox busybox Running 11 seconds ago Running docke1
# on host docker3. I got the container name and the container IP to ping test:
docker#docker3:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
fda9fb58f9d4 dhub.yunpro.cn/shenshouer/nginx:hostname "sh -c /entrypoint.sh" 7 minutes ago Up 7 minutes 80/tcp, 443/tcp nginx.1.0dvgh9xfwz7301jmsh8yc5zpe
docker#docker3:~$ docker inspect fda9fb58f9d4
...
"Networks": {
"ingress": {
"IPAMConfig": {
"IPv4Address": "10.255.0.7"
},
"Links": null,
"Aliases": [
"fda9fb58f9d4"
],
"NetworkID": "bpoqtk71o6qor8t2gyfs07yfc",
"EndpointID": "98c98a9cc0fcc71511f0345f6ce19cc9889e2958d9345e200b3634ac0a30edbb",
"Gateway": "",
"IPAddress": "10.255.0.7",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:0a:ff:00:07"
},
"mynet": {
"IPAMConfig": {
"IPv4Address": "10.0.0.3"
},
"Links": null,
"Aliases": [
"fda9fb58f9d4"
],
"NetworkID": "a1v8i656el5d3r45k985cn44e",
"EndpointID": "5f3c5678d40b6a7a2495963c16a873c6a2ba14e94cf99d2aa3fa087b67a46cce",
"Gateway": "",
"IPAddress": "10.0.0.3",
"IPPrefixLen": 24,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:0a:00:00:03"
}
}
}
}
]
# on host docker1 :
docker#docker1:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b94716e9252e busybox:latest "sleep 3000" 2 minutes ago Up 2 minutes busybox.1.9yc3svckv98xtmv1d0tvoxbeu
docker#docker1:~$ docker exec -it b94716e9252e ping nginx.1.0dvgh9xfwz7301jmsh8yc5zpe
ping: bad address 'nginx.1.0dvgh9xfwz7301jmsh8yc5zpe'
docker#docker1:~$ docker exec -it b94716e9252e ping 10.0.0.3
PING 10.0.0.3 (10.0.0.3): 56 data bytes
90 packets transmitted, 0 packets received, 100% packet loss
The third question: How to communicate with each container on the same network?
and the network mynet as:
docker#docker1:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
5ec55ffde8e4 bridge bridge local
83967a11e3dd docker_gwbridge bridge local
7f856c9040b3 host host local
bpoqtk71o6qo ingress overlay swarm
a1v8i656el5d mynet overlay swarm
829a614aa278 none null local
docker#docker1:~$ docker network inspect mynet
[
{
"Name": "mynet",
"Id": "a1v8i656el5d3r45k985cn44e",
"Scope": "swarm",
"Driver": "overlay",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "10.0.0.0/24",
"Gateway": "10.0.0.1"
}
]
},
"Internal": false,
"Containers": {
"b94716e9252e6616f0f4c81e0c7ef674d7d5f4fafe931953fced9ef059faeb5f": {
"Name": "busybox.1.9yc3svckv98xtmv1d0tvoxbeu",
"EndpointID": "794be0e92b34547e44e9a5e697ab41ddd908a5db31d0d31d7833c746395534f5",
"MacAddress": "02:42:0a:00:00:05",
"IPv4Address": "10.0.0.5/24",
"IPv6Address": ""
}
},
"Options": {
"com.docker.network.driver.overlay.vxlanid_list": "257"
},
"Labels": {}
}
]
docker#docker2:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
da07b3913bd4 bridge bridge local
7a2e627634b9 docker_gwbridge bridge local
e8971c2b5b21 host host local
bpoqtk71o6qo ingress overlay swarm
c37de5447a14 none null local
docker#docker3:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
06eb8f0bad11 bridge bridge local
fb5e3bcae41c docker_gwbridge bridge local
e167d97cd07f host host local
bpoqtk71o6qo ingress overlay swarm
a1v8i656el5d mynet overlay swarm
6540ece8e146 none null local
docker#docker3:~$ docker network inspect mynet
[
{
"Name": "mynet",
"Id": "a1v8i656el5d3r45k985cn44e",
"Scope": "swarm",
"Driver": "overlay",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "10.0.0.0/24",
"Gateway": "10.0.0.1"
}
]
},
"Internal": false,
"Containers": {
"fda9fb58f9d46317ef1df60e597bd14214ec3fac43e32f4b18a39bb92925aa7e": {
"Name": "nginx.1.0dvgh9xfwz7301jmsh8yc5zpe",
"EndpointID": "5f3c5678d40b6a7a2495963c16a873c6a2ba14e94cf99d2aa3fa087b67a46cce",
"MacAddress": "02:42:0a:00:00:03",
"IPv4Address": "10.0.0.3/24",
"IPv6Address": ""
}
},
"Options": {
"com.docker.network.driver.overlay.vxlanid_list": "257"
},
"Labels": {}
}
]
So The fourth question: Is there have build-int kv store?
Question 1: the networks on other hosts are created on demand, when swarm allocate task on that host, the network will be created.
Question 2: The load balancing works out of box, there's maybe some problem with you docker swarm cluster. you need to check the iptables and ipvs rules
Question 3: containers on the same overlay network (mynet in your case) can talk with each other, and docker has a buildin dns server which can resolve container name to ip address
Question 4: yes they do.

How to get a Docker container's IP address from the host

Is there a command I can run to get the container's IP address right from the host after a new container is created?
Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.
The --format option of inspect comes to the rescue.
Modern Docker client syntax is:
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
Old Docker client syntax is:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
These commands will return the Docker container's IP address.
As mentioned in the comments: if you are on Windows, use double quotes " instead of single quotes ' around the curly braces.
You can use docker inspect <container id>.
For example:
CID=$(docker run -d -p 4321 base nc -lk 4321);
docker inspect $CID
First get the container ID:
docker ps
(First column is for container ID)
Use the container ID to run:
docker inspect <container ID>
At the bottom, under NetworkSettings, you can find IPAddress
Or just do for UNIX based:
docker inspect <container id> | grep "IPAddress"
And for Windows CMD:
docker inspect <container id> | findstr "IPAddress"
docker inspect CONTAINER_ID | grep "IPAddress"
You can add -i to grep for ignoring the case then even the following will work:
docker inspect CONTAINER_ID | grep -i "IPaDDreSS"
To get all container names and their IP addresses in just one single command.
docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}' $(docker ps -aq)
If you are using docker-compose the command will be this:
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
The output will be:
/containerA - 172.17.0.4
/containerB - 172.17.0.3
/containerC - 172.17.0.2
Add this shell script in your ~/.bashrc or relevant file:
docker-ip() {
docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$#"
}
Then, to get an IP address of a container, simply do this:
docker-ip YOUR_CONTAINER_ID
For the new version of the Docker, please use the following:
docker-ip() {
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$#"
}
In Docker 1.3+, you can also check it using:
Enter the running Docker (Linux):
docker exec [container-id or container-name] cat /etc/hosts
172.17.0.26 d8bc98fa4088
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.17 mysql
For windows:
docker exec [container-id or container-name] ipconfig
Show all container's IP addresses:
docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
As of Docker version 1.10.3, build 20f81dd
Unless you told Docker otherwise, Docker always launches your containers in the bridge network. So you can try this command below:
docker network inspect bridge
Which should then return a Containers section which will display the IP address for that running container.
[
{
"Name": "bridge",
"Id": "40561e7d29a08b2eb81fe7b02736f44da6c0daae54ca3486f75bfa81c83507a0",
"Scope": "local",
"Driver": "bridge",
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.17.0.0/16"
}
]
},
"Containers": {
"025d191991083e21761eb5a56729f61d7c5612a520269e548d0136e084ecd32a": {
"Name": "drunk_leavitt",
"EndpointID": "9f6f630a1743bd9184f30b37795590f13d87299fe39c8969294c8a353a8c97b3",
"IPv4Address": "172.17.0.2/16",
"IPv6Address": ""
}
},
"Options": {
"com.docker.network.bridge.default_bridge": "true",
"com.docker.network.bridge.enable_icc": "true",
"com.docker.network.bridge.enable_ip_masquerade": "true",
"com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
"com.docker.network.bridge.name": "docker0",
"com.docker.network.driver.mtu": "1500"
}
}
]
My answer:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} %tab% {{.Name}}' $(docker ps -aq
) | sed 's#%tab%#\t#g' | sed 's#/##g' | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n
Also as a bash alias:
docker-ips() { docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} %tab% {{.Name}}' $(docker ps -aq) | sed 's#%tab%#\t#g' | sed 's#/##g' | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n }
Output is sorted by IP address, and tab delimited:
# docker-ips
172.18.0.2 memcached
172.18.0.3 nginx
172.18.0.4 fpm-backup
172.18.0.5 dns
172.18.0.6 fpm-beta
172.18.0.7 exim
172.18.0.8 fpm-delta
172.18.0.9 mariadb
172.18.0.10 fpm-alpha
172.19.0.2 nextcloud-redis
172.19.0.3 nextcloud-db
172.19.0.4 nextcloud
Execute:
docker ps -a
This will display active docker images:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3b733ae18c1c parzee/database "/usr/lib/postgresql/" 6 minutes ago Up 6 minutes 5432/tcp serene_babbage
Use the CONTAINER ID value:
docker inspect <CONTAINER ID> | grep -w "IPAddress" | awk '{ print $2 }' | head -n 1 | cut -d "," -f1
"172.17.0.2"
Based on some of the answers I loved, I decided to merge them to a function to get all the IP addresses and another for an specific container. They are now in my .bashrc file.
docker-ips() {
docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
}
docker-ip() {
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$#"
}
The first command gives the IP address of all the containers and the second a specific container's IP address.
docker-ips
docker-ip YOUR_CONTAINER_ID
Docker is written in Go and it uses Go syntax for query purposes too.
To inspect the IP address of a particular container, you need to run the command (-f for "format"):
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id_or_name
For the container ID or name, you can run the command
docker container ls
which will list every running container.
I wrote the following Bash script to get a table of IP addresses from all containers running under docker-compose.
function docker_container_names() {
docker ps -a --format "{{.Names}}" | xargs
}
# Get the IP address of a particular container
dip() {
local network
network='YOUR-NETWORK-HERE'
docker inspect --format "{{ .NetworkSettings.Networks.$network.IPAddress }}" "$#"
}
dipall() {
for container_name in $(docker_container_names);
do
local container_ip=$(dip $container_name)
if [[ -n "$container_ip" ]]; then
echo $(dip $container_name) " $container_name"
fi
done | sort -t . -k 3,3n -k 4,4n
}
You should change the variable network to your own network name.
Here's a quick working answer:
Get your container name or ID:
docker container ls
Then get the IP:
docker inspect <container_ID Or container_name> |grep 'IPAddress'
Get the port:
docker inspect <container_ID Or container_name> |grep 'Port'
Reference containers by name:
docker run ... --name pg-master
Then grab the IP address address by name:
MASTER_HOST=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' pg-master)
Here's is a solution that I developed today in Python, using the docker inspect container JSON output as the data source.
I have a lot of containers and infrastructures that I have to inspect, and I need to obtain basic network information from any container, in a fast and pretty manner. That's why I made this script.
IMPORTANT: Since the version 1.9, Docker allows you to create multiple networks and attach them to the containers.
#!/usr/bin/python
import json
import subprocess
import sys
try:
CONTAINER = sys.argv[1]
except Exception as e:
print "\n\tSpecify the container name, please."
print "\t\tEx.: script.py my_container\n"
sys.exit(1)
# Inspecting container via Subprocess
proc = subprocess.Popen(["docker","inspect",CONTAINER],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out = proc.stdout.read()
json_data = json.loads(out)[0]
net_dict = {}
for network in json_data["NetworkSettings"]["Networks"].keys():
net_dict['mac_addr'] = json_data["NetworkSettings"]["Networks"][network]["MacAddress"]
net_dict['ipv4_addr'] = json_data["NetworkSettings"]["Networks"][network]["IPAddress"]
net_dict['ipv4_net'] = json_data["NetworkSettings"]["Networks"][network]["IPPrefixLen"]
net_dict['ipv4_gtw'] = json_data["NetworkSettings"]["Networks"][network]["Gateway"]
net_dict['ipv6_addr'] = json_data["NetworkSettings"]["Networks"][network]["GlobalIPv6Address"]
net_dict['ipv6_net'] = json_data["NetworkSettings"]["Networks"][network]["GlobalIPv6PrefixLen"]
net_dict['ipv6_gtw'] = json_data["NetworkSettings"]["Networks"][network]["IPv6Gateway"]
for item in net_dict:
if net_dict[item] == "" or net_dict[item] == 0:
net_dict[item] = "null"
print "\n[%s]" % network
print "\n{}{:>13} {:>14}".format(net_dict['mac_addr'],"IP/NETWORK","GATEWAY")
print "--------------------------------------------"
print "IPv4 settings:{:>16}/{:<5} {}".format(net_dict['ipv4_addr'],net_dict['ipv4_net'],net_dict['ipv4_gtw'])
print "IPv6 settings:{:>16}/{:<5} {}".format(net_dict['ipv6_addr'],net_dict['ipv6_net'],net_dict['ipv6_gtw'])
The output is:
$ python docker_netinfo.py debian1
[frontend]
02:42:ac:12:00:02 IP/NETWORK GATEWAY
--------------------------------------------
IPv4 settings: 172.18.0.2/16 172.18.0.1
IPv6 settings: null/null null
[backend]
02:42:ac:13:00:02 IP/NETWORK GATEWAY
--------------------------------------------
IPv4 settings: 172.19.0.2/16 172.19.0.1
IPv6 settings: null/null null
I use this simple way
docker exec -it <container id or name> hostname -i
e.g
ubuntu#myhost:~$ docker exec -it 3d618ac670fe hostname -i
10.0.1.5
docker inspect --format '{{ .NetworkSettings.IPAddress }}' <containername or containerID here>
The above works if the container is deployed to the default bridge network.
However, if using a custom bridge network or a overlay network, I found the below to work better:
docker exec <containername or containerID here> /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
To extend ko-dos' answer, here's an alias to list all container names and their IP addresses:
alias docker-ips='docker ps | tail -n +2 | while read -a a; do name=${a[$((${#a[#]}-1))]}; echo -ne "$name\t"; docker inspect $name | grep IPAddress | cut -d \" -f 4; done'
NOTE!!! for Docker Compose Usage:
Since Docker Compose creates an isolated network for each cluster, the methods below do not work with docker-compose.
The most elegant and easy way is defining a shell function, currently the most-voted answer #WouterD's:
dockip() {
docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$#"
}
Docker can write container IDs to a file like Linux programs:
Running with --cidfile=filename, Docker dumps the ID of the container to "filename".
See "Docker runs PID equivalent Section" for more information.
--cidfile="app.cid": Write the container ID to the file
Using a PID file:
Running container with --cidfile parameter, the app.cid file content is like:
a29ac3b9f8aebf66a1ba5989186bd620ea66f1740e9fe6524351e7ace139b909
You can use file content to inspect Docker containers:
blog-v4 git:(develop) ✗ docker inspect `cat app.cid`
You can extract the container IP using an inline Python script:
$ docker inspect `cat app.cid` | python -c "import json;import sys;\
sys.stdout.write(json.load(sys.stdin)[0]['NetworkSettings']['IPAddress'])"
172.17.0.2
Here's a more human friendly form:
#!/usr/bin/env python
# Coding: utf-8
# Save this file like get-docker-ip.py in a folder that in $PATH
# Run it with
# $ docker inspect <CONTAINER ID> | get-docker-ip.py
import json
import sys
sys.stdout.write(json.load(sys.stdin)[0]['NetworkSettings']['IPAddress'])
See "10 alternatives of getting the Docker container IP addresses" for more information.
Combining previous answers with finding the container ID based on the Docker image name:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' `docker ps | grep $IMAGE_NAME | sed 's/\|/ /' | awk '{print $1}'`
Just for completeness:
I really like the --format option, but at first I wasn't aware of it so I used a simple Python one-liner to get the same result:
docker inspect <CONTAINER> |python -c 'import json,sys;obj=json.load(sys.stdin);print obj[0]["NetworkSettings"]["IPAddress"]'
For those who came from Google to find a solution for command execution from the terminal (not by a script), "jid", which is an interactive JSON drill-down utility with autocomplete and suggestion, lets you do the same thing with less typing.
docker inspect $CID | jid
Type Tab .Net Tab and you'll see something like:
[Filter]> .[0].NetworkSettings
{
"Bridge": "",
"EndpointID": "b69eb8bd4f11d8b172c82f21ab2e501fe532e4997fc007ed1a997750396355d5",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"HairpinMode": false,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"Aliases": null,
"EndpointID": "b69eb8bd4f11d8b172c82f21ab2e501fe532e4997fc007ed1a997750396355d5",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
Type .IPA Tab and you'll see something like:
[Filter]> .[0].NetworkSettings.IPAddress
"172.17.0.2"
If you installed Docker using Docker Toolbox, you can use the Kitematic application to get the container IP address:
Select the container
Click on Settings
Click in Ports tab.
The accepted answer does not work well with multiple networks per container:
> docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' cc54d96d63ea
172.20.0.4172.18.0.5
The next best answer is closer:
> docker inspect cc54d96d63ea | grep "IPAddress"
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.20.0.4",
"IPAddress": "172.18.0.5",
I like to use jq to parse the network JSON:
> docker inspect cc54d96d63ea | jq -r 'map(.NetworkSettings.Networks) []'
{
"proxy": {
"IPAMConfig": null,
"Links": [
"server1_php_1:php",
"server1_php_1:php_1",
"server1_php_1:server1_php_1"
],
"Aliases": [
"cc54d96d63ea",
"web"
],
"NetworkID": "7779959d7383e9cef09c970c38c24a1a6ff44695178d314e3cb646bfa30d9935",
"EndpointID": "4ac2c26113bf10715048579dd77304008904186d9679cdbc8fcea65eee0bf13b",
"Gateway": "172.20.0.1",
"IPAddress": "172.20.0.4",
"IPPrefixLen": 24,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:14:00:04",
"DriverOpts": null
},
"webservers": {
"IPAMConfig": null,
"Links": [
"server1_php_1:php",
"server1_php_1:php_1",
"server1_php_1:server1_php_1"
],
"Aliases": [
"cc54d96d63ea",
"web"
],
"NetworkID": "907a7fba8816cd0ad89b7f5603bbc91122a2dd99902b504be6af16427c11a0a6",
"EndpointID": "7febabe380d040b96b4e795417ba0954a103ac3fd37e9f6110189d9de92fbdae",
"Gateway": "172.18.0.1",
"IPAddress": "172.18.0.5",
"IPPrefixLen": 24,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:12:00:05",
"DriverOpts": null
}
}
To list the IP addresses of every container then becomes:
for s in `docker ps -q`; do
echo `docker inspect -f "{{.Name}}" ${s}`:
docker inspect ${s} | jq -r 'map(.NetworkSettings.Networks) []' | grep "IPAddress";
done
/server1_web_1:
"IPAddress": "172.20.0.4",
"IPAddress": "172.18.0.5",
/server1_php_1:
"IPAddress": "172.20.0.3",
"IPAddress": "172.18.0.4",
/docker-gen:
"IPAddress": "172.18.0.3",
/nginx-proxy:
"IPAddress": "172.20.0.2",
"IPAddress": "172.18.0.2",
To get the IP address and host port of a container:
docker inspect containerId | awk '/IPAddress/ || /HostPort/'
Output:
"HostPort": "4200"
"HostPort": "4200"
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
For windows 10:
docker inspect --format "{{ .NetworkSettings.IPAddress }}" containerId
This will list down all the container IPs on the host:
sudo docker ps -aq | while read line; do sudo docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $line ; done
Docker inspect use to print all container ips and its respective names
docker ps -q | xargs -n 1 docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} {{ .Name }}' | sed 's/ \// /'

Resources