Networking With Docker
So we’ve talked about containers and how can you create multiple containers, but the question is how we can connect containers so they can talk to each other, the answer for that is Docker networks
You’ve actually already been using Docker networks if you’ve booted up even one container. Every container that’s started up is connected to a personal virtual network called bridge
You can see a list of your current Docker networks by using docker network ls
The bridge
driver creates a personal network internal to the host so containers on this network can communicate. External access to a container is granted by exposing ports of containers. Docker secures the network by managing rules that block connectivity between different Docker networks. Bridge networks apply to containers running on an equivalent Docker daemon host.
User defined Networks
User-defined bridge networks are superior to the default bridge network. you need to always be creating your own network whenever you’re running multiple containers. There are several reasons to always create your own network:
- User-defined bridges provide automatic DNS resolution between containers.
- User-defined bridges provide better isolation.
- Containers can be attached and detached from user-defined networks on the fly.
- Each user-defined network creates a configurable bridge.
- Linked containers on the default bridge network share environment variables.
For more explanation check the doc
For example I will create two containers and connect them to each other
Run this command to create database
container from redis
image: docker container run -d --name database redis:alpine
Create another container with name docker container run -d --name nginx nginx:alpine
Create new network by running this code docker network create new_network
Untill now new_network
doesn’t have containers related to it, let’s make sure by runnig this code docker network inspect new_network
We can connect our containers that we created earlier to our new_network
by running this code docker network connect new_network database && docker network connect new_network nginx
Now is time to make our two containers to talk to each other docker container exec -it nginx ping database
As you see now the containers talking to each other