Docker Network
By default, all containers are connected to a virtual network bridge create by docker. They can access each other by IP address. However, the IP address is not fixed and may be different each time the container is started.
Docker provides us a way to use container names instead of IP address.
Common Docker Network Commands
docker network create
: create a networkdocker network ls
: check all networksdocker network rm
: remove a networkdocker network inspect
: check details of a certain networkdocker network prune
: clear unused local networksdocker network connect
: add a container to a certain networkdocker network disconnect
: remove a container from a networkdocker network --help
Usage with Examples
To connect a existing container to a network:
docker network create myNetwork
docker network connect myNetwork mysql
docker inspect mysql
Now you should see two items under network.
To connect a container to a network when creating the container
docker run -d --name nginx2 -p 80:80 --network myNetwork nginx
docker inspect nginx2
There should be only one item under network. The container will not be connected to the default network.
After executing the commands above, you can use container names just like localhost
to access containers under the same (custom) network.
ping mysql