Networking in Docker-Compose
One of the many confusing things for beginners is how networking works in Docker-Compose.
Itās essentially you āDatacenter on a Laptopā. That means you can have virtual switches, routers and vpcās, all on your laptop.
In this lecture weāre having a closer look at how this exactly works!
Understanding the Basic Docker Bridge and Host Network
By default, docker creates an overlay network over all containers. A bridge. Itās called ādocker0ā. From the previous lectures there should be some networks left:
docker network ls
- Brings up a list of all networks
docker network prune
- Should delete all networks
- Just to clean up ā you donāt have to do this, but sometimes itās good to start fresh
docker network ls
- Should now just list the necessary networks for docker to function
- A bridge
- A host
- A null
docker run --rm --name my-webserver -d httpd
- Start an apache webserver (httpd container)
- Detached (
-d
)
docker inspect my-webserver
-
Check the IP address of the container Open http://172.17.0.2ā (or the IP address of your container)
-
It wonāt let you connect to it
-
Unless you forward a port to your host with -p 8080:80 or soā¦
docker run --rm tomw1808/mycurl my-webserver
- Should download and run an image called ātomw1808/curlā which is just an ubuntu alpine with curl installed
- And curl āmy-webserverā
- Basically, the same as executing
curl my-webserver
on any Linux
- Basically, the same as executing
- It will end in an error
docker run --rm tomw1808/mycurl 172.17.0.2
- Will output you the HTML of the Webserver
- āIt Works!ā
So, we canāt curl by name, we have to curl the exact IP Address
docker stop my-webserver
- Stops the webserver container
Hostname binding with Docker
Letās see if we can also get Hostname-binding to work with Dockerā¦
docker network create simple-network
- Creates a new bridge network called āsimple-networkā
docker run --rm -d --name my-webserver --network simple-network httpd
- Start the webserver again attaching it to the āsimple-networkā we created earlier
docker run --rm --network simple-network appropriate/curl my-webserver
- Now the name binding works
- āIt Works!ā
docker inspect my-webserver
- Get the IP Address of your webserver
- It should be 172.22.0.2 (or so ā copy the IP of your container here)
docker run --rm tomw1808/mycurl IP-OF-MY-WEBSERVER(e.g. 172.22.0.2)
- Run curl without the network, on the docker0 network
- You wonāt be able to connect to the webserver
- Itās segregated from the other network
- Ctrl-c to stop
docker stop my-webserver
- Stop the container again
docker network rm simple-network
- Cleanup: remove the simple-network again