当前位置: 首页 > 编程文章 >

Docker网络原理及自定义网络详细解析

Docker网络原理及自定义网络详细解析

作者:陆川时间:2026-07-03 10:37:46浏览:373

Docker默认使用docker0虚拟网桥为容器分配IP,但外网无法直接访问且容器间仅支持IP通信。通过link修改hosts可实现单向名称解析,而自定义网络允许指定子网并支持容器名双向互通。本文演示了从默认网络到自定义网络的创建、连接及跨网络通信配置方法。

本文目录收起

Docker在宿主机层面构建了一个虚拟网桥。每当创建并启动容器时,系统会默认为其分配一个与该网桥处于同一网段的IP地址。该网桥充当容器的网关,连接所有容器以实现内部通信。由于网桥是虚拟接口,外部网络无法对其进行寻址,因此默认情况下外网不能直接访问容器内容。若需从外部访问,必须在启动容器时将宿主机的端口映射到容器端口,通过宿主机IP和端口进行访问。这是Docker的默认网络模式,其局限性在于容器间只能通过IP地址相互访问。若希望使用容器名称或ID进行通信,需在启动时使用link参数修改hosts文件来实现。通常建议采用自定义网络,通过network命令创建时可指定子网和网关等参数,并在启动容器时指定使用该网络。在此模式下,同一自定义网络内的容器可直接通过名称互相访问;若需跨网络通信,也可在network配置中设置,使不同网络的容器能通过名称进行通信。

1 默认网络docker0

在VM虚拟机环境中进行测试,在未启动Docker服务前,系统中存在两个网络:回环网络和虚拟机网络。

启动Docker服务后,宿主机新增名为docker0的网络,这便是Docker的默认网络。


# 启动docker服务
[root@localhost ~]# systemctl start docker

启动一个Tomcat容器后,宿主机会观察到多出一个新的网络接口。


启动tomcat
[root@localhost ~]# docker run -d -P --name tomcat1 tomcat

再次启动另一个Tomcat容器,宿主机会继续增加一个新的网络接口。


# 启动tomcat
[root@localhost ~]# docker run -d -P --name tomcat2 tomcat

测试发现,这两个Tomcat容器的网络IP之间是互通的。


# 查看tomcat的ip地址
[root@localhost ~]# docker exec -it tomcat2 ip addr
1: lo:  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:  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
# 在tomcat1 ping tomcat2的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

在Tomcat1容器中尝试ping Tomcat2的容器名,结果显示无法连通。


# 在tomcat1里ping tomcat2的容器名
[root@localhost ~]# docker exec -it tomcat1 ping tomcat2
^C[root@localhost ~]#

停止Tomcat1并重新创建启动,使用link参数会在底层修改Tomcat1的hosts文件,将容器名映射为IP域名,从而实现从Tomcat1到Tomcat2的单向ping通。


# 删除tomcat1
[root@localhost ~]# docker rm -f tomcat1
tomcat1
 
# 查看run的帮助文档 link用法
[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: [:])
      --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
 
# 启动tomcat1 link指定要访问的容器名
[root@localhost ~]# docker run -d -P --name tomcat1 --link tomcat2 tomcat
f78c51961662a1d3558fc8d0d95906b902a7a042f251a60858e72bcfa62e7a08
 
# 测试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
 
# 查看tomcat1的hosts已经加入了tomcat2的域名
[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无法ping通tomcat1
[root@localhost ~]# docker exec -it tomcat2 ping tomcat1
^C[root@localhost ~]#

2 自定义网络

此功能需要使用network命令进行操作。


# 查看帮助文档
[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.

列出当前Docker网络,其中bridge即为默认的docker0网络。


[root@localhost ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
9b27ff0926bf   bridge    bridge    local
8dfa2efae677   host      host      local
2026b7fb1d7c   none      null      local

创建一个名为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": "2026-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": {}
    }
]

使用mynet网络创建并启动两个Tomcat容器,它们可以直接通过容器名称实现双向互相ping通。


[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: [:])
      --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

查看mynet网络的详细信息,其中包含了已启动的两个Tomcat容器的具体网络信息。


[root@localhost ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "1abaa8e6a387bc8bbc7ac50d9f2289e96a143a92f074e90f698bd70411c86672",
        "Created": "2026-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": {
            "404e4e63622b207af2ed534e768996f4d1cba4c798bba9e5d9b33c42711eaa4a": {
                "Name": "tomcat-n-1",
                "EndpointID": "b9efbd78daabe9345ade2a2e55291b7646d01679516e2f0be1efd5c2d6fea6b8",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "f6352fb3db01beed6ddf17ef84999a4ab209f026a6137b3bc7e35335d434785f": {
                "Name": "tomcat-n-2",
                "EndpointID": "6b05a1ceff43514305bf3d0adf9e30ba8007db5ec8349d47f96ff2b216912fc0",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

启动一个名为tomcat3的容器,并使用默认的docker0网络。


[root@localhost ~]# docker run -d -P --name tomcat3 tomcat
90e94ac30a3c61b493d2ea38c32cf5dddb781e88c30547b609db765b15d7d1e0
[root@localhost ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
9b27ff0926bf   bridge    bridge    local
8dfa2efae677   host      host      local
1abaa8e6a387   mynet     bridge    local
2026b7fb1d7c   none      null      local
 
# 查看docker0详细信息 tomcat3出现在默认网络里
[root@localhost ~]# docker network inspect 9b27ff0926bf
[
    {
        "Name": "bridge",
        "Id": "9b27ff0926bf22d0828ccd07d6e14eb17d96a4989f9def6f9118c099cf1ca1c6",
        "Created": "2026-05-13T10:51:20.244232273+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "27766c324de619b24e2ed522d8064c5a4610c8f509ff0aed8fa1719691f01bf1": {
                "Name": "tomcat2",
                "EndpointID": "de913778ce2d7478e25daca26809aa75c9093c43853d9420c70886fb16741722",
                "MacAddress": "02:42:ac:11:00:03",
                "IPv4Address": "172.17.0.3/16",
                "IPv6Address": ""
            },
            "90e94ac30a3c61b493d2ea38c32cf5dddb781e88c30547b609db765b15d7d1e0": {
                "Name": "tomcat3",
                "EndpointID": "2223e522a0950b846bb7691b31f60bbd88ab3c9b8e71d601a495cce39387b8cc",
                "MacAddress": "02:42:ac:11:00:04",
                "IPv4Address": "172.17.0.4/16",
                "IPv6Address": ""
            },
            "f78c51961662a1d3558fc8d0d95906b902a7a042f251a60858e72bcfa62e7a08": {
                "Name": "tomcat1",
                "EndpointID": "59299fdca5497e55dc5a94e408529cc98819b673568720c81aa1c554dff1bbe5",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

由于tomcat3与mynet不在同一网络,tomcat3无法直接访问mynet中的两个Tomcat容器。可以通过network命令打通tomcat3和mynet,实现双向互相访问(支持容器名称)。


# 查看mynet网络里容器的ip
[root@localhost ~]# docker network inspect mynet
[
    {
        "Name": "mynet",
        "Id": "1abaa8e6a387bc8bbc7ac50d9f2289e96a143a92f074e90f698bd70411c86672",
        "Created": "2026-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": {
            "404e4e63622b207af2ed534e768996f4d1cba4c798bba9e5d9b33c42711eaa4a": {
                "Name": "tomcat-n-1",
                "EndpointID": "b9efbd78daabe9345ade2a2e55291b7646d01679516e2f0be1efd5c2d6fea6b8",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
            "f6352fb3db01beed6ddf17ef84999a4ab209f026a6137b3bc7e35335d434785f": {
                "Name": "tomcat-n-2",
                "EndpointID": "6b05a1ceff43514305bf3d0adf9e30ba8007db5ec8349d47f96ff2b216912fc0",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]
 
# tomcat3 ping ip不通
[root@localhost ~]# docker exec -it tomcat3 ping 192.168.0.2
PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data.
^C
--- 192.168.0.2 ping statistics ---
7 packets transmitted, 0 received, 100% packet loss, time 11ms
 
[root@localhost ~]# docker exec -it tomcat3 ping 192.168.0.3
PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.
^C
--- 192.168.0.3 ping statistics ---
9 packets transmitted, 0 received, 100% packet loss, time 20ms

# 使用connect联通一个网络和另外一个网络里的容器,可以互相容器名称访问
[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

以上就是Docker网络原理及自定义网络详细解析的详细内容,更多关于docker网络原理的资料请关注本站其它相关文章!

上一篇
Docker部署RocketMQ全流程指南:从环境搭建到常见问题排查

本文记录使用 Docker Compose 搭建 RocketMQ 服务端及可视化控制台的过程。通过拉取官方镜像、编写 broker.conf 配置文件及 docker-compose.yml,实现 Namesrv、Broker 和 Console 的一键启动。同时针对消息发送超时、控制台无法连接 Namesrv 等常见报错,提供了基于 IP 配置和环境变量修正的具体解决方案。

下一篇
Dockerfile 构建指令详解与 CMD/ENTRYPOINT 场景测试

Dockerfile 是定义 Docker 镜像构建流程的核心文本文件,包含基础镜像、操作指令及启动命令。本文详细解析 FROM、RUN、COPY、ADD、ENV、ARG 等关键指令的语法与作用域差异,重点对比 CMD 与 ENTRYPOINT 在执行机制上的不同,并通过 Kubernetes YAML 配置覆盖场景的实测,阐明 command 和 args 对默认配置的覆盖逻辑。

相关文章

更多
Docker容器跨网络互联:加入同一网络实现IP与域名互通

本文介绍如何让处于不同Docker网络下的容器实现互联互通。通过将其他网络中的容器加入到目标自定义网络(如mynet),该容器将获得第二个IP地址并接入新网络。配置完成后,源容器既可以通过目标容器的IP地址进行通信,也可以利用Docker内置的DNS服务通过容器名称直接访问,操作简便且高效。

2025.10.13 845
Docker容器访问宿主机的多种实现方案

在Docker容器中直接访问127.0.0.1仅指向容器自身,无法连接宿主机服务。针对Mac和Linux环境,可通过配置/etc/hosts、使用--add-host参数或专用域名如docker.for.mac.host.internal来实现容器对宿主机的网络访问。其核心原理是利用Docker创建的虚拟网桥docker0获取宿主机的网关地址。

2026.06.19 808
Docker容器网络请求缓慢的DNS解析优化方案

在使用Docker进行npm install或API数据获取时,常因DNS解析延迟导致请求超时。本文分析Docker的四种网络模式及DNS解析机制,指出瓶颈主要在域名解析阶段。通过修改/etc/hosts映射内网IP或指定外部nameserver(如223.5.5.5),可显著加速容器内的网络请求。

2025.04.23 651
Docker 网络配置与容器互联详解

本文详解 Docker 基础网络配置,涵盖随机映射端口、指定地址端口绑定及 UDP 端口设置等外部访问方式。介绍通过 docker network create 创建自定义桥接网络以实现容器间通信,并深入解析基于 --link 参数的旧版容器互联机制,包括安全隧道建立、环境变量注入及 /etc/hosts 文件更新原理。

2025.04.11 495
Docker设置固定IP的方法与自定义网络配置

Docker默认bridge网络在重启后会导致容器IP地址变化,影响MongoDB副本集等需要绑定内网IP的服务部署。通过创建指定子网的自定义网络并在使用docker run时添加--ip参数,可为容器分配静态IP。本文介绍三种默认网络类型的区别及固定IP的具体操作步骤。

2026.10.23 479
Docker容器访问宿主机网络的两种方法

在Docker容器中运行Nginx反向代理时,若配置指向localhost可能因网络隔离导致502错误。本文介绍通过查询docker0网关IP(如Linux下的172.17.0.1)或启用--network host模式来解决此问题。前者需硬编码IP且跨环境兼容性差,后者共享宿主网络但牺牲了部分隔离安全性。

2026.09.08 447

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。