There is something that I don't understand about the process of IPs allocation in the docker network mechanism.
Suppose I run a few containers. Each gets its own IP address - from where these IP addresses came from?
If one of the container listen to a port, and I go to the browser and write the <IP>:<PORT>
and see the webpage - How does my computer know to resolve that (That this is a local IP address)?
相关问题
- Docker task in Azure devops won't accept "$(pw
- Unable to run mariadb when mount volume
- Unspecified error (0x80004005) while running a Doc
- What would prevent code running in a Docker contai
- How to reload apache in php-apache docker containe
A full discussion of Docker networking is out of scope here, so I'll just assume from your question you're talking about
bridge
networking (which is the default).When you start the Docker daemon (
dockerd
) it creates a ethernet bridge network interface on your local machine calleddocker0
.This can be customized if neccessary but usually defaults are fine.
This is represented in Docker as a network called
bridge
:Notice the
inet addr
/Gateway
are the same. Also notice:To answer one part of your question, your container IP addresses are allocated from this subnet (
172.17.0.0/16
) that Docker creates. Now we know some networking stuff has been setup, let's run a container and see what happens.We can see that this container has an ip address on my bridge network:
In fact, I can use that IP address and the container port to hit my app (try
172.17.0.2:5000
in your browser!). However this is not very scalable / dynamic as this IP address could change when my container is restarted. Also I had to do a bunch of stuff to find it.Instead of having to do that, I am mapping port 7000 on my host machine to port 5000 in my container (this is the port my application is listening on) so I can visit
localhost:7000
in my browser and hit my app (try that too!).OK great, so what makes the traffic to port 7000 on my machine magically route to port 5000 in my container?
Let's take a look at
iptables
!:The (most) important line as far as we're concerned here is the one I've left in above. It says "for all traffic not coming from the docker0 interface (
! -i docker0
), using the TCP protocol (-p tcp
), destined for port 7000 (--dport 7000
) , actually route it to 172.17.0.2:5000 (--to-destination 172.17.0.2:5000
)". That is a little simplified of course, but essentially what's going on.Now if you start another container (this time let's bind to host port 9999):
And do a quick check of it's IP:
Now
iptables
again:Notice we now have another rule, same structure, this time saying for all traffic to port 9999, send to our new container IP (
--to-destination 172.17.0.3:5000
).Stop the containers and you'll notice these rules disappear!
IANA networking expert, so some stuff might be a little simplified but hope it helps!