iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >如何在Docker中自定义网络
  • 230
分享到

如何在Docker中自定义网络

2023-06-15 02:06:54 230人浏览 八月长安
摘要

本篇文章给大家分享的是有关如何在Docker中自定义网络,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1 默认网络docker0用vm虚拟机测试,未启动docker 系统中有两

本篇文章给大家分享的是有关如何在Docker中自定义网络,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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 addr1: 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 forever9: 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# 在tomcat1 ping tomcat2的ip[root@localhost ~]# docker exec -it tomcat1 ping 172.17.0.3PING 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 ms64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.067 ms64 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 5msrtt min/avg/max/mdev = 0.067/0.100/0.146/0.034 ms

在tomcat1里ping tomcat2的 容器名无法ping通

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

停止tomcat1 重新创建启动tomcat 使用link 会在底层修改tomcat1 的hosts文件 实现容器名作为ip域名从而tomcat1到tomcat2的单向ping通

# 删除tomcat1[root@localhost ~]# docker rm -f tomcat1tomcat1 # 查看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: <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 # 启动tomcat1 link指定要访问的容器名[root@localhost ~]# docker run -d -P --name tomcat1 --link tomcat2 tomcatf78c51961662a1d3558fc8d0d95906b902a7a042f251a60858e72bcfa62e7a08 # 测试ping[root@localhost ~]# docker exec -it tomcat1 ping tomcat2PING 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 ms64 bytes from tomcat2 (172.17.0.3): icmp_seq=2 ttl=64 time=0.071 ms64 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 1000msrtt min/avg/max/mdev = 0.071/0.076/0.088/0.012 ms # 查看tomcat1的hosts已经加入了tomcat2的域名[root@localhost ~]# docker exec -it tomcat1 cat /etc/hosts127.0.0.1       localhost::1     localhost ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allrouters172.17.0.3      tomcat2 27766c324de6172.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 lsNETWORK ID     NAME      DRIVER    SCOPE9b27ff0926bf   bridge    bridge    local8dfa2efae677   host      host      local2025b7fb1d7c   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 mynet1abaa8e6a387bc8bbc7ac50d9f2289e96a143a92f074e90f698bd70411c86672[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": {}    }]

使用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: <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 tomcat404e4e63622b207af2ed534e768996f4d1cba4c798bba9e5d9b33c42711eaa4a[root@localhost ~]# docker run -d -P --name tomcat-n-2 --network mynet tomcatf6352fb3Db01beed6ddf17ef84999a4ab209f026a6137b3bc7e35335d434785f[root@localhost ~]# docker psCONTAINER ID   IMAGE     COMMAND             CREATED          STATUS          PORTS                                         NAMESf6352fb3db01   tomcat    "catalina.sh run"   3 seconds ago    Up 2 seconds    0.0.0.0:49159->8080/tcp, :::49159->8080/tcp   tomcat-n-2404e4e63622b   tomcat    "catalina.sh run"   10 seconds ago   Up 9 seconds    0.0.0.0:49158->8080/tcp, :::49158->8080/tcp   tomcat-n-1f78c51961662   tomcat    "catalina.sh run"   15 minutes ago   Up 15 minutes   0.0.0.0:49157->8080/tcp, :::49157->8080/tcp   tomcat127766c324de6   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-2PING 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 ms64 bytes from tomcat-n-2.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.069 ms64 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 3msrtt 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": "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": {            "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 tomcat90e94ac30a3c61b493d2ea38c32cf5DDDb781e88c30547b609db765b15d7d1e0[root@localhost ~]# docker network lsNETWORK ID     NAME      DRIVER    SCOPE9b27ff0926bf   bridge    bridge    local8dfa2efae677   host      host      local1abaa8e6a387   mynet     bridge    local2025b7fb1d7c   none      null      local # 查看docker0详细信息 tomcat3出现在默认网络里[root@localhost ~]# docker network inspect 9b27ff0926bf[    {        "Name": "bridge",        "Id": "9b27ff0926bf22d0828ccd07d6e14eb17d96a4989f9def6f9118c099cf1ca1c6",        "Created": "2021-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和mynetwork,实现双向互相访问(支持容器名称)。

# 查看mynet网络里容器的ip[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": {            "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.2PING 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.3PING 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-1PING 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 ms64 bytes from tomcat-n-1.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.070 ms64 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 6msrtt min/avg/max/mdev = 0.064/0.123/0.235/0.079 ms[root@localhost ~]# docker exec -it tomcat-n-1 ping tomcat3PING 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 ms64 bytes from tomcat3.mynet (192.168.0.4): icmp_seq=2 ttl=64 time=0.169 ms64 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 6msrtt min/avg/max/mdev = 0.055/0.139/0.194/0.061 ms

以上就是如何在Docker中自定义网络,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网精选频道。

--结束END--

本文标题: 如何在Docker中自定义网络

本文链接: http://www.lsjlt.com/news/276627.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何在Docker中自定义网络
    本篇文章给大家分享的是有关如何在Docker中自定义网络,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1 默认网络docker0用vm虚拟机测试,未启动docker 系统中有两...
    99+
    2023-06-15
  • Docker如何自定义网络
    这篇文章将为大家详细讲解有关Docker如何自定义网络,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。Docker自定义网络一.自定义网络介绍介绍常规docker容器启动,可以用–link,进行容器网络绑定...
    99+
    2023-06-22
  • docker如何自定义网络问题
    目录首先看看网卡的信息docker网络原理veth-pair技术容器互联 --link容器互联 - 自定义网络总结首先看看网卡的信息 通过ip addr命令可以看到,这里有三个网卡,...
    99+
    2023-03-12
    docker自定义网络 docker网络 自定义网络
  • Docker如何实现自定义网络
    小编给大家分享一下Docker如何实现自定义网络,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!1、自定义网络实现容器互联四类网络模式,使用docker netwo...
    99+
    2023-06-22
  • Docker之自定义网络实现
    目录1、自定义网络实现容器互联2、网络连通1、自定义网络实现容器互联 四类网络模式,使用docker network ls查看docker网络模式 ...
    99+
    2024-04-02
  • docker怎么自定义网络问题
    本文小编为大家详细介绍“docker怎么自定义网络问题”,内容详细,步骤清晰,细节处理妥当,希望这篇“docker怎么自定义网络问题”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。首先看看网卡的信息通过ip add...
    99+
    2023-07-05
  • Docker自定义网络详细介绍
    目录Docker自定义网络一.自定义网络介绍二.创建自定义网络Docker自定义网络 一.自定义网络介绍 1.介绍 常规docker容器启动,可以用–link,进行容器网络绑定,但是...
    99+
    2024-04-02
  • Docker网络原理及自定义网络详细解析
    Docker在宿主机上虚拟了一个网桥,当创建并启动容器的时候,每一个容器默认都会被分配一个跟网桥网段一致的ip,网桥作为容器的网关,网桥与每一个容器联通,容器间通过网桥可以通信。由于...
    99+
    2024-04-02
  • docker中Dockerfile如何自定义mycentos
    这篇文章主要为大家展示了“docker中Dockerfile如何自定义mycentos”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“docker中Dockerfile如何自定义mycentos”...
    99+
    2023-06-04
  • docker 容器自定义 hosts 网络访问操作
    在 docker-compose.yml 中增加 extra_hosts 关键字就可以将数据写入到容器的 /etc/hosts。 extra_hosts 添加主机名映射。 ex...
    99+
    2024-04-02
  • docker中Dockerfile如何自定义tomcat镜像
    小编给大家分享一下docker中Dockerfile如何自定义tomcat镜像,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!   &...
    99+
    2023-06-04
  • 如何在Android中自定义ProgressBar
    如何在Android中自定义ProgressBar?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。具体如下:<xml version="...
    99+
    2023-05-30
    android progressbar
  • 如何在zabbix中自定义key
    这篇文章主要介绍了如何在zabbix中自定义key,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。 如何在zabbix中自定义key,并使用...
    99+
    2024-04-02
  • 如何在Android中自定义Dialog
    本篇文章为大家展示了如何在Android中自定义Dialog,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。功能:android 提供给我们的只有2种Dialog 即 AlertDialog &...
    99+
    2023-05-31
    android roi dialog
  • 如何在Torch中定义一个神经网络模型
    在Torch中定义一个神经网络模型通常需要使用nn.Module类。下面是一个示例代码,展示了如何定义一个简单的全连接神经网络模型:...
    99+
    2024-04-02
  • 如何在PaddlePaddle中定义一个神经网络模型
    在PaddlePaddle中定义一个神经网络模型通常需要以下几个步骤: 导入相应的库:首先需要导入PaddlePaddle的相关...
    99+
    2024-04-02
  • 如何在css中自定义属性
    本篇文章给大家分享的是有关如何在css中自定义属性,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1* css变量的语法<1> 什么是css变量?如果您使用过任何一种...
    99+
    2023-06-08
  • 如何在Html5中自定义字体
    如何在Html5中自定义字体?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。第一步:使用@font-faceMDN概述这是一个叫做@font-face 的CSS ...
    99+
    2023-06-09
  • 如何在shell中自定义函数
    这篇文章给大家介绍如何在shell中自定义函数,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。一,调用函数必须在定义函数的后,不然会报错的funfun (){ echo "aaaa...
    99+
    2023-06-09
  • 如何在PHP中自定义函数
    在PHP中,函数是一组可重复使用的代码块,它们通过一个名称来标识。PHP支持大量现成的函数,如array_push、explode等,但有时候你需要编写自己的函数以实现特定的功能或提高代码复用性。在这篇文章中,我将介绍如何在PHP中自定义函...
    99+
    2023-05-18
    函数编程 自定义函数 PHP编程
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作