Skip to content

Day 10 - Docker Networking Basics

Published:Β atΒ 12:00 AM

On Day 5 you learned that Docker containers have some network isolation. Today, we’re going to dive deeper into Docker networking and learn how containers can communicate with each other!

Publishing Ports Refresher

Remember our HTTP server from Day 5? By default, containers are isolated and we needed to publish ports to access them from our host:

$ docker run -p 8080:8080 hello-world-go

The -p flag maps port 8080 from the container to port 8080 on your host. You can also map to a different host port:

$ docker run -p 3000:8080 hello-world-go

Publishing All Ports

If your container exposes multiple ports (using the EXPOSE instruction), you can publish all of them at once with -P:

$ docker run -P hello-world-go

Docker will automatically assign random host ports. Use docker ps to see the mappings:

$ docker ps
CONTAINER ID   IMAGE           PORTS                     NAMES
abc123def456   hello-world-go  0.0.0.0:55000->8080/tcp  cool_name

Container Communication

What if containers need to talk to each other? Let’s create a simple network:

$ docker network create myapp-network

Now run two containers on this network:

$ docker run -d --name api --network myapp-network hello-world-go
$ docker run -d --name frontend --network myapp-network nginx

Containers on the same network can reach each other using their container names as hostnames! From inside the frontend container:

$ docker exec -it frontend curl http://api:8080
Hello World!

Network Types

Docker supports several network types:

You can read more about network drivers in the official documentation.

Custom Hostnames

While Docker uses container names as hostnames by default, you can set custom ones:

$ docker run --name api --hostname custom-api --network myapp hello-world-go

Now other containers on the network can reach this container using either api or custom-api as the hostname.

You can verify the hostname from inside the container:

$ docker exec -it api hostname
custom-api

That’s it for today! Tomorrow we’ll look at Docker Compose, which makes managing multiple containers and networks much easier.

Until then, happy coding! πŸ³πŸŽ„

Jonas


Previous Post
Day 8 - Quiz Solutions
Next Post
Day 11 - Docker Compose Introduction
Sponsor logo

Sliplane

Deploy your Docker Apps straight from your Github repository in less than 2 minutes with sliplane.io

Learn More β†’