10 Docker Networks Intro - dchantzis/sfh-docker-in-development-part-1 GitHub Wiki
Source: https://serversforhackers.com/c/div-docker-networks-intro
We will see how we can get containers to talk to each other over a Docker network.
We will create two containers and add them into the new network appnet.
The containers then can reference eachother - the hostname for each container is taken from the --name
given to the container. This lets the app container talk to mysql over hostname mysql
.
Within the container, you can run getent hosts mysql
to see the hostname resolution of hostname mysql
To list the default Docker networks:
docker network ls
Below we will create a new network and create two additional containers and make them communicate with each other.
docker network create appnet
docker network ls
We will create a MySQL Container and hook it up with the application container so that they can communicate with each other:
We will go to https://hub.docker.com/_/mysql
and use the MySQL 5.7
docker run --rm -d --name=mysql --network=appnet -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=homestead -e MYSQL_USER=homestead -e MYSQL_USER_PASSWORD=secret mysql:5.7
- --name The name of the host
We can check everything:
docker image ls
docker network ls
docker network inspect appnet
The last command will show us the containers inside the appnet
network.
We can check the IPv4 Address used for the host that we named mysql
Next:
docker exec -it mysql bash
which mysql
getent hosts mysql
mysql -h mysql -u root -p
- -h Is the host that we named
mysql
inside the container
Now we will create the second Container under the same network appnet
:
docker run --name=app --network=appnet -d --rm -p 80:80 -v %cd%/application:/var/www/html/public shippingdocker/app:latest
To see them both running (mysql
and app
):
docker ps
Bash into app
:
docker exec -it app bash
Then check the IP address of the host app
:
getent hosts app
Check the IP address of the host mysql
(this means they can see each other):
getent hosts mysql
Exit the container and inspect the network appnet
to view both of the Containers of the network:
docker network inspect appnet