Get port details for a container:
docker container port <container-name>
# 80/tcp -> 0.0.0.0:80
# 80/tcp -> :::80
Get IP for container:
docker container inspect --format '{{ .NetworkSettings.IPAddress }}' webhost
--format
- option for formatting the output of commands using Go templates
How networking happens with Docker containers?
Virtual networks get created when we publish a container. For example, if we publish container C1 with 80:80
,
it means any traffic coming in at port 80 on the host will be forwarded to port 80 on container C1 via the virtual network. Creating another container C2 by default, will be put in the same virtual network, which means, C1 and C2 can communicate freely via this virtual network.
NOTE: A host port can only be linked to one container.
Bridge or Docker0 is the default virtual network mapped to the host IP.
Docker Network CLI commands
Show all networks:
docker network ls
Inspect a network:
docker network inspect <network-name>
Create a virtual network:
docker network create <network-name>
To use a custom bridge, we can use the
--driver
option.
Attach a network to a container:
docker network connect <network-name> <container-name>
Detach a network from a container:
docker network disconnect <network-name> <container-name>
Connect to a network while running a container:
docker container run -d --name <container-name> --network <network-name> <image>
Default network types
Bridge or Docker0 - the default virtual network mapped to the host IP. It allows containers to communicate with each other when running on the same docker host.
host - a special network that attaches the container directly to the host by skipping the virtual network.
none - Only
localhost
interface is available in container
Using Docker networks, we can ensure that:
- related apps are on the same Docker network
- Their inter-communication is restricted to the virtual network
- Traffics can be forwarded from host to container only if we publish the container with
--publish
or-p
DNS
Containers can communicate with other containers in the same virtual network with host names.
Docker defaults host name to container's name. However, we can also use aliases.
To provide network aliases for containers, we can do the following:
docker container run --rm --network <network-name> --network-alias <container-network-alias> <image>
So, with this containers in the same virtual network can communicate with each other via aliases.
The flag
--rm
makes sure the container is deleted permanently on exit.
Top comments (0)