Docker Networking
Docker Networking
Network Drivers Types
- bridge - this is the default and most used network driver.
- host - remove network isolation between host and container, use host’s networking directly. Host mode networking can be useful to optimize performance.
- overlay - Overlay networks connect multiple Docker daemons together and enable swarm services to communicate with each other.
- none - disable all networking. Container can’t connect to network. Not used often.
When a container is connected to a network, it can communicate with other containers in the same network.
List Networks
1 | docker network ls |
default output
1 | NETWORK ID NAME DRIVER SCOPE |
Create a Network
use docker network create
to create network. use -d
or --driver
option to set the driver type
1 | docker network create -d bridge my-bridge |
You can specify the network’s subnet and gateway. The prefix length is 16 by default, here we can specify a subnet with prefix length of24.
1 | docker network create -d bridge --subnet 172.66.66.0/24 --gateway 172.66.66.1 my-bridge |
run ifconfig
on the host machine, you will see a new network interface added.
1 | $ ifconfig |
Inspect a Network
1 | docker network inspect my-bridge |
This will show the network information such as Subnet and Gateway information.
It will also contain the containers connected to the network and their IP addresses.
Sample output:
1 | $ docker network inspect my-bridge |
Remove a Network
1 | docker network rm my-bridge |
Running a container in a Network
use --net=<network>
or --network=<network>
option to specify the network. <network>
is the name of the network to be used
1 | docker run -it --rm --network bridge --name my-alpine alpine |
Disconnect from a network
1 | docker network disconnect bridget my-alpine |
Connect to my-bridge network
1 | docker network connect my-bridge my-alpine |
The above command will automatically assign an IP address to the container. You can connect to a network with a specified IP address.
1 | docker network connect --ip 172.66.66.33 my-bridge my-alpine |
Inspect the container’s network configuration.
1 | docker exec my-alpine ifconfig |
Example: Run Containers on the Same Network
Here is an example bash script to run both mysql and phpmyadmin container on the same network
1 |
|
We first create a bridge network called sample-network. Then create mysql and phpmyadmin container that both connect to sample-network.
You can now open phpmyadmin at http://localhost:7000/