In this post we are going to look at docker networks in a sort of crash course.
- We start with learning what types of networks there are
- We then look at a simple example with alpine containers and ping
1.) Which types of Networks exist
The first one allows to use the docker hosts machine network stack directly.
The second one allwos the container to have a MAC address so it can be used as a physical device.
The third allows multiple docker daemons on different machines to communicate with each other.
The fourth one allows to connect different containers on the same machine to connect together. This is also the default network all containers are added to when none is specified.
(post is a WIP)
2.) Simple example with alpine containers
Examples teach best in my opinion that is why we use a simple one here.
- Start two alpine containers
- inspect one of them to learn about their IP Address
- Ping from the other container to that IP Address
- Discover why this is not the best way to use docker networks
We start the containers like so:
docker container run --name alpine-1 -it alpine sh
& (in another terminal)
docker container run --name alpine-2 -it alpine sh
Then we inspect the container called alpine-2 in a third terminal and find the IP address:
docker container inspect alpine-2
This gives us a json document, and at the very end of it we can see the IP Address:
Then we can ping the other container with the following command (from the terminal with alpine-1 container)
What is the issue with this?
If we want to utilize this for more complex scenarios we need to inspect the network address for each container individually and manually because they are chosen randomly on startup.
To avoid this and use built in docker mechanisms we want to utilize the docker DNS to resolve the container by their name.
For this we need to create a simple network of type bridge (which is the default) like so:
docker network create alpine-net
And then we can connect both containers to it:
docker network connect alpine-net alpine-1
docker network connect alpine-net alpine-2
The other option is to stop the containers and run them directly connected to the network:
docker container run --name alpine-1 --network=alpine-net -it alpine sh
And now we can inspect the alpine-net with the command
docker network inspect alpine-net
We can then again ping one of the containers from inside the other one, yet by using their names and not their ip address.
So this is the most easy approach to networking, and this is exactly the way it is set up when you utilize docker-compose.
We explored networking with docker with an easy example. We learned how to utilize the docker DNS to refer to containers by their container name instead of their IP-address.
Also we looked at the different available network types and what they can do for you.