Principle of Docker Network and Detailed Analysis of Custom Network
- 2021-10-27 10:03:19
- OfStack
Docker virtualizes a bridge on the host machine. When containers are created and started, each container will be assigned an ip with bridge segment 1 by default. The bridge acts as the gateway of the container, and the bridge communicates with each container, and the containers can communicate through the bridge. Because the bridge is virtual, the external network cannot be addressed, that is, the external network cannot access the container by default. When creating the startup container, the port of the host machine should be mapped with the container port, and the container should be accessed through the IP port of the host machine. This is the default network of Docker, which has one drawback is that containers can only access each other through IP. If you want to use container name or container ID to access each other, you need to modify hosts file in the way of link when creating startup container. 1 general use of custom network, custom network use network to create, create can specify subnet segment and gateway information, create and start the container to specify the use of the network. In this way, all containers in a custom network can be accessed directly by using the container name. If a container wants to access containers in other networks, it can also be set in network, so that this container can communicate with containers in the target network by using the container name.
1 default network docker0
Tested with vm virtual machine, there are two networks (loop-back network and virtual machine network) in the unstarted docker system
When the docker service is started, the host has an extra network docker0, which is the default network of docker
# Start docker Services
[root@localhost ~]# systemctl start docker
If you start an tomcat container, you will find that there is another network on the host machine
Start tomcat
[root@localhost ~]# docker run -d -P --name tomcat1 tomcat
Starting one more tomcat will develop one more host network
# Start tomcat
[root@localhost ~]# docker run -d -P --name tomcat2 tomcat
Test that two tomcat networks ip are connected
# View tomcat Adj. ip Address
[root@localhost ~]# docker exec -it tomcat2 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
9: eth0@if10: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
# In tomcat1 ping tomcat2 Adj. ip
[root@localhost ~]# docker exec -it tomcat1 ping 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.146 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.067 ms
64 bytes from 172.17.0.3: icmp_seq=3 ttl=64 time=0.088 ms
^C
--- 172.17.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 5ms
rtt min/avg/max/mdev = 0.067/0.100/0.146/0.034 ms
In tomcat1, the container name of ping tomcat2 cannot be passed through ping
# In tomcat1 Li ping tomcat2 Container name of
[root@localhost ~]# docker exec -it tomcat1 ping tomcat2
^C[root@localhost ~]#
Stop tomcat1, recreate and start tomcat. Using link will modify the hosts file of tomcat1 in the bottom layer to realize the container name as ip domain name, so as to realize one-way ping communication from tomcat1 to tomcat2
# Delete tomcat1
[root@localhost ~]# docker rm -f tomcat1
tomcat1
# View run Help documentation for link Usage
[root@localhost ~]# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container
Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
-a, --attach list Attach to STDIN, STDOUT or STDERR
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device list Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--cgroup-parent string Optional parent cgroup for the container
--cgroupns string Cgroup namespace to use (host|private)
'host': Run the container in the Docker host's cgroup namespace
'private': Run the container in its own private cgroup namespace
'': Use the cgroup namespace as configured by the
default-cgroupns-mode option on the daemon (default)
--cidfile string Write the container ID to the file
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container
--device-cgroup-rule list Add a rule to the cgroup allowed devices list
--device-read-bps list Limit read rate (bytes per second) from a device (default [])
--device-read-iops list Limit read rate (IO per second) from a device (default [])
--device-write-bps list Limit write rate (bytes per second) to a device (default [])
--device-write-iops list Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers
--dns-option list Set DNS options
--dns-search list Set custom DNS search domains
--domainname string Container NIS domain name
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
--expose list Expose a port or a range of ports
--gpus gpu-request GPU devices to add to the container ('all' to pass all GPUs)
--group-add list Add additional groups to join
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-start-period duration Start period for the container to initialize before starting health-retries countdown
(ms|s|m|h) (default 0s)
--health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
-i, --interactive Keep STDIN open even if not attached
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
--kernel-memory bytes Kernel memory limit
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
--log-driver string Logging driver for the container
--log-opt list Log driver options
--mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--mount mount Attach a filesystem mount to the container
--name string Assign a name to the container
--network network Connect a container to a network
--network-alias list Add network-scoped alias for the container
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--platform string Set platform if server is multi-platform capable
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--pull string Pull image before running ("always"|"missing"|"never") (default "missing")
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options
--shm-size bytes Size of /dev/shm
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string Working directory inside the container
# Start tomcat1 link Specify the name of the container to access
[root@localhost ~]# docker run -d -P --name tomcat1 --link tomcat2 tomcat
f78c51961662a1d3558fc8d0d95906b902a7a042f251a60858e72bcfa62e7a08
# Test ping
[root@localhost ~]# docker exec -it tomcat1 ping tomcat2
PING tomcat2 (172.17.0.3) 56(84) bytes of data.
64 bytes from tomcat2 (172.17.0.3): icmp_seq=1 ttl=64 time=0.088 ms
64 bytes from tomcat2 (172.17.0.3): icmp_seq=2 ttl=64 time=0.071 ms
64 bytes from tomcat2 (172.17.0.3): icmp_seq=3 ttl=64 time=0.071 ms
^C
--- tomcat2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.071/0.076/0.088/0.012 ms
# View tomcat1 Adj. hosts Has joined tomcat2 Domain name of
[root@localhost ~]# docker exec -it tomcat1 cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 tomcat2 27766c324de6
172.17.0.2 f78c51961662
# tomcat2 Unable to ping Tong tomcat1
[root@localhost ~]# docker exec -it tomcat2 ping tomcat1
^C[root@localhost ~]#
2 Custom Network
The network command is required
# View Help Documentation
[root@localhost ~]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
Run 'docker network COMMAND --help' for more information on a command.
List the current docker network bridge as the default network docker0
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
9b27ff0926bf bridge bridge local
8dfa2efae677 host host local
2025b7fb1d7c none null local
Create a network mynet
[root@localhost ~]# docker network create --help
Usage: docker network create [OPTIONS] NETWORK
Create a network
Options:
--attachable Enable manual container attachment
--aux-address map Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])
--config-from string The network from which to copy the configuration
--config-only Create a configuration only network
-d, --driver string Driver to manage the Network (default "bridge")
--gateway strings IPv4 or IPv6 Gateway for the master subnet
--ingress Create swarm routing-mesh network
--internal Restrict external access to the network
--ip-range strings Allocate container ip from a sub-range
--ipam-driver string IP Address Management Driver (default "default")
--ipam-opt map Set IPAM driver specific options (default map[])
--ipv6 Enable IPv6 networking
--label list Set metadata on a network
-o, --opt map Set driver specific options (default map[])
--scope string Control the network's scope
--subnet strings Subnet in CIDR format that represents a network segment
[root@localhost ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
1abaa8e6a387bc8bbc7ac50d9f2289e96a143a92f074e90f698bd70411c86672
[root@localhost ~]# docker network inspect mynet
[
{
"Name": "mynet",
"Id": "1abaa8e6a387bc8bbc7ac50d9f2289e96a143a92f074e90f698bd70411c86672",
"Created": "2021-05-13T11:21:13.494039122+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "192.168.0.0/16",
"Gateway": "192.168.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {},
"Options": {},
"Labels": {}
}
]
Use mynet to create and start two tomcat, which can communicate to each other ping directly by container name in both directions
[root@localhost ~]# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container
Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
-a, --attach list Attach to STDIN, STDOUT or STDERR
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device list Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--cgroup-parent string Optional parent cgroup for the container
--cgroupns string Cgroup namespace to use (host|private)
'host': Run the container in the Docker host's cgroup namespace
'private': Run the container in its own private cgroup namespace
'': Use the cgroup namespace as configured by the
default-cgroupns-mode option on the daemon (default)
--cidfile string Write the container ID to the file
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container
--device-cgroup-rule list Add a rule to the cgroup allowed devices list
--device-read-bps list Limit read rate (bytes per second) from a device (default [])
--device-read-iops list Limit read rate (IO per second) from a device (default [])
--device-write-bps list Limit write rate (bytes per second) to a device (default [])
--device-write-iops list Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers
--dns-option list Set DNS options
--dns-search list Set custom DNS search domains
--domainname string Container NIS domain name
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
--expose list Expose a port or a range of ports
--gpus gpu-request GPU devices to add to the container ('all' to pass all GPUs)
--group-add list Add additional groups to join
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-start-period duration Start period for the container to initialize before starting health-retries countdown
(ms|s|m|h) (default 0s)
--health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
-i, --interactive Keep STDIN open even if not attached
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
--kernel-memory bytes Kernel memory limit
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
--log-driver string Logging driver for the container
--log-opt list Log driver options
--mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--mount mount Attach a filesystem mount to the container
--name string Assign a name to the container
--network network Connect a container to a network
--network-alias list Add network-scoped alias for the container
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--platform string Set platform if server is multi-platform capable
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--pull string Pull image before running ("always"|"missing"|"never") (default "missing")
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options
--shm-size bytes Size of /dev/shm
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string Working directory inside the container
[root@localhost ~]# docker run -d -P --name tomcat-n-1 --network mynet tomcat
404e4e63622b207af2ed534e768996f4d1cba4c798bba9e5d9b33c42711eaa4a
[root@localhost ~]# docker run -d -P --name tomcat-n-2 --network mynet tomcat
f6352fb3db01beed6ddf17ef84999a4ab209f026a6137b3bc7e35335d434785f
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f6352fb3db01 tomcat "catalina.sh run" 3 seconds ago Up 2 seconds 0.0.0.0:49159->8080/tcp, :::49159->8080/tcp tomcat-n-2
404e4e63622b tomcat "catalina.sh run" 10 seconds ago Up 9 seconds 0.0.0.0:49158->8080/tcp, :::49158->8080/tcp tomcat-n-1
f78c51961662 tomcat "catalina.sh run" 15 minutes ago Up 15 minutes 0.0.0.0:49157->8080/tcp, :::49157->8080/tcp tomcat1
27766c324de6 tomcat "catalina.sh run" 16 minutes ago Up 16 minutes 0.0.0.0:49156->8080/tcp, :::49156->8080/tcp tomcat2
[root@localhost ~]# docker exec -it tomcat-n-1 ping tomcat-n-2
PING tomcat-n-2 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat-n-2.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.102 ms
64 bytes from tomcat-n-2.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from tomcat-n-2.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.164 ms
^C
--- tomcat-n-2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.069/0.111/0.164/0.041 ms
View the details of the mynet network, including the network information of the two tomcat containers started
Start tomcat
[root@localhost ~]# docker run -d -P --name tomcat1 tomcat
0
Start 1 tomcat3 using the default network docker0
Start tomcat
[root@localhost ~]# docker run -d -P --name tomcat1 tomcat
1
tomcat3 and mynet are not in the same network, and tomcat3 cannot access two tomcat in mynet network. network can be used to open tomcat3 and mynetwork to realize bidirectional mutual access (container name is supported).
Start tomcat
[root@localhost ~]# docker run -d -P --name tomcat1 tomcat
2
# Use connect Unicom 1 Networks and other 1 Containers in the network can be accessed by mutual container names
[root@localhost ~]# docker network connect --help
Usage: docker network connect [OPTIONS] NETWORK CONTAINER
Connect a container to a network
Options:
--alias strings Add network-scoped alias for the container
--driver-opt strings driver options for the network
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--link list Add link to another container
--link-local-ip strings Add a link-local address for the container
[root@localhost ~]# docker network connect mynet tomcat3
[root@localhost ~]# docker exec -it tomcat3 ping tomcat-n-1
PING tomcat-n-1 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-n-1.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.235 ms
64 bytes from tomcat-n-1.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.070 ms
64 bytes from tomcat-n-1.mynet (192.168.0.2): icmp_seq=3 ttl=64 time=0.064 ms
^C
--- tomcat-n-1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 6ms
rtt min/avg/max/mdev = 0.064/0.123/0.235/0.079 ms
[root@localhost ~]# docker exec -it tomcat-n-1 ping tomcat3
PING tomcat3 (192.168.0.4) 56(84) bytes of data.
64 bytes from tomcat3.mynet (192.168.0.4): icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from tomcat3.mynet (192.168.0.4): icmp_seq=2 ttl=64 time=0.169 ms
64 bytes from tomcat3.mynet (192.168.0.4): icmp_seq=3 ttl=64 time=0.194 ms
^C
--- tomcat3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 6ms
rtt min/avg/max/mdev = 0.055/0.139/0.194/0.061 ms
The above is the Docker network principle and custom network detailed analysis of the details, more information about docker network principle please pay attention to other related articles on this site!