• docker容器间通信 (共用宿主机)


         本文讨论同一宿主机下不同docker容器间通信的解决方案,比如宿主机下PHP的web服务容器需要连接mysql容器就会用到接下来说的方法。

         正常情况下,我们安装完docker会创建一个默认网桥docker0    

    #手动安装brctl命令
    [root@new2 dockerfile]# brctl show
    bridge name    bridge id        STP enabled    interfaces
    br-72a0e7df683d        8000.0242ea904416    no        
    br-8c32615c1dea        8000.0242723a4063    no        vethe3eb576
                                vethfa75006
    docker0        8000.0242e12e8e06    no    

      同是docker安装后会默认创建三个网络:bridge/host/name,其中bridge模式是docker默认使用的网络

    [root@new2 dockerfile]# docker network ls
    NETWORK ID          NAME                   DRIVER              SCOPE
    350b170c0117        bridge                 bridge              local
    8610e4eb9359        host                   host                local
    f8d2652c4dec        none                   null                local
    
    Docker四种网络工作模式:
    #host:容器将不会虚拟出自己的网卡,配置自己的IP等,而是使用宿主机的IP和端口,使用--net=host指定;
    #Container:创建的容器不会创建自己的网卡,配置自己的IP,而是和一个指定的容器共享IP、端口范围,使用 --net=container:NAME_or_ID指定;
    #None:关闭了容器的网络功能,使用--net=none指定;
    #Bridge:为每一个容器分配、设置IP等,并将容器连接到一个docker0虚拟网桥,通过docker0网桥以及Iptables nat表配置与宿主机通信,使用--net=bridge指定,默认设置;

    docker容器间通信可以使用link和bridge网桥,不过link后期可能要被移除,官方也不推荐使用。

    https://docs.docker.com/network/links/

    这里主要说自定义bridge网络来实现容器间通信

    docker1.10版本开始内嵌一个DNS server,方便容器间通过“”容器名“通信。使用默认的bridge网络,不能通过DNS server实现容器名通信,不过我们可以使用自定义bridge网络来实现。

      首先看下使用默认bridge网桥配置的容器通信情况:

      

    #这里指定80端口,因为镜像创建时,已指定需要通过80端口访问容器
    [root@new2 ~]# docker run -d -p 80 --name="centos_default_bridge" mycentos_from_dockerfile:v2 /bin/bash
    703d2d4cb2cec56f4c539fa2dbe687c0b91be8cd2c50de76086bdc665a185366
    [root@new2 ~]# docker run -d -p 80 --name="centos_default_bridge" mycentos_from_dockerfile:v2 /bin/bash
    8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33
    
    #看下centos_default_bridge2配置,可见其IP地址为:172.17.0.2
    [root@new2 ~]# docker inspect centos_default_bridge2
    [
        {
            "Id": "8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33",
            "Created": "2020-07-11T14:43:09.949852828Z",
            "Path": "/bin/bash",
            "Args": [],
            "State": {
                "Status": "running",
                "Running": true,
                "Paused": false,
                "Restarting": false,
                "OOMKilled": false,
                "Dead": false,
                "Pid": 27461,
                "ExitCode": 0,
                "Error": "",
                "StartedAt": "2020-07-11T14:43:10.231446816Z",
                "FinishedAt": "0001-01-01T00:00:00Z"
            },
            "Image": "sha256:4b1edd50a106bb6dfec2cd161e39f9874a215ee064364967aac80f1cc50082bb",
            "ResolvConfPath": "/var/lib/docker/containers/8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33/resolv.conf",
            "HostnamePath": "/var/lib/docker/containers/8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33/hostname",
            "HostsPath": "/var/lib/docker/containers/8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33/hosts",
            "LogPath": "/var/lib/docker/containers/8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33/8103a5b3ab458de4cb2c94faae407f1db3cea20050611e0847492b2605c1ee33-json.log",
            "Name": "/centos_default_bridge2",
            "RestartCount": 0,
            "Driver": "overlay2",
            "Platform": "linux",
            "MountLabel": "",
            "ProcessLabel": "",
            "AppArmorProfile": "",
            "ExecIDs": null,
            "HostConfig": {
                "Binds": null,
                "ContainerIDFile": "",
                "LogConfig": {
                    "Type": "json-file",
                    "Config": {}
                },
                "NetworkMode": "default",
                "PortBindings": {
                    "80/tcp": [
                        {
                            "HostIp": "",
                            "HostPort": ""
                        }
                    ]
                },
                "RestartPolicy": {
                    "Name": "no",
                    "MaximumRetryCount": 0
                },
                "AutoRemove": false,
                "VolumeDriver": "",
                "VolumesFrom": null,
                "CapAdd": null,
                "CapDrop": null,
                "Capabilities": null,
                "Dns": [],
                "DnsOptions": [],
                "DnsSearch": [],
                "ExtraHosts": null,
                "GroupAdd": null,
                "IpcMode": "private",
                "Cgroup": "",
                "Links": null,
                "OomScoreAdj": 0,
                "PidMode": "",
                "Privileged": false,
                "PublishAllPorts": false,
                "ReadonlyRootfs": false,
                "SecurityOpt": null,
                "UTSMode": "",
                "UsernsMode": "",
                "ShmSize": 67108864,
                "Runtime": "runc",
                "ConsoleSize": [
                    0,
                    0
                ],
                "Isolation": "",
                "CpuShares": 0,
                "Memory": 0,
                "NanoCpus": 0,
                "CgroupParent": "",
                "BlkioWeight": 0,
                "BlkioWeightDevice": [],
                "BlkioDeviceReadBps": null,
                "BlkioDeviceWriteBps": null,
                "BlkioDeviceReadIOps": null,
                "BlkioDeviceWriteIOps": null,
                "CpuPeriod": 0,
                "CpuQuota": 0,
                "CpuRealtimePeriod": 0,
                "CpuRealtimeRuntime": 0,
                "CpusetCpus": "",
                "CpusetMems": "",
                "Devices": [],
                "DeviceCgroupRules": null,
                "DeviceRequests": null,
                "KernelMemory": 0,
                "KernelMemoryTCP": 0,
                "MemoryReservation": 0,
                "MemorySwap": 0,
                "MemorySwappiness": null,
                "OomKillDisable": false,
                "PidsLimit": null,
                "Ulimits": null,
                "CpuCount": 0,
                "CpuPercent": 0,
                "IOMaximumIOps": 0,
                "IOMaximumBandwidth": 0,
                "MaskedPaths": [
                    "/proc/asound",
                    "/proc/acpi",
                    "/proc/kcore",
                    "/proc/keys",
                    "/proc/latency_stats",
                    "/proc/timer_list",
                    "/proc/timer_stats",
                    "/proc/sched_debug",
                    "/proc/scsi",
                    "/sys/firmware"
                ],
                "ReadonlyPaths": [
                    "/proc/bus",
                    "/proc/fs",
                    "/proc/irq",
                    "/proc/sys",
                    "/proc/sysrq-trigger"
                ]
            },
            "GraphDriver": {
                "Data": {
                    "LowerDir": "/var/lib/docker/overlay2/63be01a957afade10e8fa521537f9064b7912b0b2467974b17176ca8ea0d0c0b-init/diff:/var/lib/docker/overlay2/e26f0878029f868adb8ad43aa3081cbfce8e9d75f53da932f4d2ac55edc416f1/diff:/var/lib/docker/overlay2/a8ed9e8b220f02b57c8894633ffdd3260328dc8635a56c6c47dd75ae62fbd820/diff:/var/lib/docker/overlay2/236027395c3ba490761ea3de6d09be437ccad05161ce70cdb6122de516903110/diff:/var/lib/docker/overlay2/5d3a4eeea4718541893c89d08bae72ca2e74a03d683602a981d2dccd4f0efcfe/diff",
                    "MergedDir": "/var/lib/docker/overlay2/63be01a957afade10e8fa521537f9064b7912b0b2467974b17176ca8ea0d0c0b/merged",
                    "UpperDir": "/var/lib/docker/overlay2/63be01a957afade10e8fa521537f9064b7912b0b2467974b17176ca8ea0d0c0b/diff",
                    "WorkDir": "/var/lib/docker/overlay2/63be01a957afade10e8fa521537f9064b7912b0b2467974b17176ca8ea0d0c0b/work"
                },
                "Name": "overlay2"
            },
            "Mounts": [],
            "Config": {
                "Hostname": "8103a5b3ab45",
                "Domainname": "",
                "User": "",
                "AttachStdin": false,
                "AttachStdout": false,
                "AttachStderr": false,
                "ExposedPorts": {
                    "80/tcp": {}
                },
                "Tty": true,
                "OpenStdin": true,
                "StdinOnce": false,
                "Env": [
                    "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                    "DEBIAN_FRONTEND=noninteractive",
                    "TEST_VERSION=1.0.1",
                    "POSITION=Guangzhou.Guangdong"
                ],
                "Cmd": [
                    "/bin/bash"
                ],
                "Image": "mycentos_from_dockerfile:v2",
                "Volumes": null,
                "WorkingDir": "",
                "Entrypoint": null,
                "OnBuild": null,
                "Labels": {}
            },
            "NetworkSettings": {
                "Bridge": "",
                "SandboxID": "1fa15de81e77b2f1269f14a1c44eb5271963cdfd4984db903492b1118e582be4",
                "HairpinMode": false,
                "LinkLocalIPv6Address": "",
                "LinkLocalIPv6PrefixLen": 0,
                "Ports": {
                    "80/tcp": [
                        {
                            "HostIp": "0.0.0.0",
                            "HostPort": "32776"
                        }
                    ]
                },
                "SandboxKey": "/var/run/docker/netns/1fa15de81e77",
                "SecondaryIPAddresses": null,
                "SecondaryIPv6Addresses": null,
                "EndpointID": "58d50f77368ac19641dbf5c191761d090af674852ab658c189ee4a7951e5012e",
                "Gateway": "172.17.0.1",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "MacAddress": "02:42:ac:11:00:02",
                "Networks": {
                    "bridge": {
                        "IPAMConfig": null,
                        "Links": null,
                        "Aliases": null,
                        "NetworkID": "350b170c01176d38b5bb543c9305a2d90fbcc739e3a8619bd7691599bf491fc2",
                        "EndpointID": "58d50f77368ac19641dbf5c191761d090af674852ab658c189ee4a7951e5012e",
                        "Gateway": "172.17.0.1",
                        "IPAddress": "172.17.0.2",
                        "IPPrefixLen": 16,
                        "IPv6Gateway": "",
                        "GlobalIPv6Address": "",
                        "GlobalIPv6PrefixLen": 0,
                        "MacAddress": "02:42:ac:11:00:02",
                        "DriverOpts": null
                    }
                }
            }
        }
    ]
    
    #进入centos_default_bridge容器
    [root@new2 ~]# docker exec -it centos_default_bridge /bin/bash
    #在centos_default_bridge容器通过IP来ping容器centos_default_bridge2网络畅通
    root@703d2d4cb2ce:/# ping 172.17.0.2            
    PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
    64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.048 ms
    64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.052 ms
    64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.056 ms
    64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.054 ms
    ^C
    --- 172.17.0.2 ping statistics ---
    4 packets transmitted, 4 received, 0% packet loss, time 2999ms
    rtt min/avg/max/mdev = 0.048/0.052/0.056/0.007 ms
    #切换成centos_default_bridge2来ping,网络不通
    root@703d2d4cb2ce:/# ping centos_default_bridge2 
    ping: unknown host centos_default_bridge2

    下面新建一个自定义网络centos_expose_bridge,新增两个容器指定使用自定义网络配置

    [root@new2 dockerfile]# docker network create -d bridge centos_expose_bridge
    [root@new2 dockerfile]# docker network ls
    NETWORK ID          NAME                   DRIVER              SCOPE
    350b170c0117        bridge                 bridge              local
    8c32615c1dea        centos_expose_bridge   bridge              local
    72a0e7df683d        dnmp_default           bridge              local
    8610e4eb9359        host                   host                local
    f8d2652c4dec        none                   null                local
    
    #基于同一镜像创建指定网络的容器
    [root@new2 dockerfile]# docker run -d --name centos_bridge --network centos_expose_bridge mycentos:v2 /bin/bash
    [root@new2 dockerfile]# docker run -d --name centos_bridge --network centos_expose_bridge mycentos:v2 /bin/bash
    [root@new2 dockerfile]# docker network inspect centos_expose_bridge
    [
        {
            "Name": "centos_expose_bridge",
            "Id": "8c32615c1dea401220d12dfd7720171f32f1bacc057977c560cac27c91725738",
            "Created": "2020-07-11T17:18:21.824462131+08:00",
            "Scope": "local",
            "Driver": "bridge",
            "EnableIPv6": false,
            "IPAM": {
                "Driver": "default",
                "Options": {},
                "Config": [
                    {
                        "Subnet": "172.19.0.0/16",
                        "Gateway": "172.19.0.1"
                    }
                ]
            },
            "Internal": false,
            "Attachable": false,
            "Ingress": false,
            "ConfigFrom": {
                "Network": ""
            },
            "ConfigOnly": false,
            "Containers": {
                "37d696620875695a73936b39c62fd3eac191683f89f5da701a11f4ea9e37b45e": {
                    "Name": "docker_expose",
                    "EndpointID": "d5525bf34381dc4d6b77649e1e28d61c90af86f08855c5830f4907e53bf74fc1",
                    "MacAddress": "02:42:ac:13:00:02",
                    "IPv4Address": "172.19.0.2/16",
                    "IPv6Address": ""
                },
                "94c0b5178358def497bdad5d74ca609c2456309feeb111979217d3944d1c6ba2": {
                    "Name": "docker_expose2",
                    "EndpointID": "3ef1e63cbc1bbacc97b2375d81d83564a4a85c38fc72d12767181ba71031a652",
                    "MacAddress": "02:42:ac:13:00:03",
                    "IPv4Address": "172.19.0.3/16",
                    "IPv6Address": ""
                }
            },
            "Options": {},
            "Labels": {}
        }
    ]
    #进入其中centos_expose容器ping一下centos_expose2容器,可见是可以直ping容器名的
    [root@new2 ~]# docker exec -it docker_expose /bin/bash
    root@37d696620875:/# ping docker_expose2
    PING docker_expose2 (172.19.0.3) 56(84) bytes of data.
    64 bytes from docker_expose2.centos_expose_bridge (172.19.0.3): icmp_seq=1 ttl=64 time=0.042 ms
    64 bytes from docker_expose2.centos_expose_bridge (172.19.0.3): icmp_seq=2 ttl=64 time=0.054 ms
    
    #容器的hosts文件并没有centos_expose2映射配置
    root@37d696620875:/# 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.19.0.2    37d696620875
    
    #再看下DNS服务解析配置,可见指向127.0.0.11地址,使用默认bridge网络的容器在resolv.conf不会出现该地址
    root@37d696620875:/# cat /etc/resolv.conf 
    nameserver 127.0.0.11
    options timeout:1 rotate ndots:0
  • 相关阅读:
    111
    ZeroClipBoard 复制粘贴插件
    三、新增临时素材
    二、获取AccessToken
    一、微信公众平台的接入微信公众平台的接入
    Jquery.validate的使用
    尝试解决IIS问题一些方法
    匿名类和匿名方法
    泛型类的认知
    发布支持mysql8.0的writer和reader
  • 原文地址:https://www.cnblogs.com/wscsq789/p/13285148.html
Copyright © 2020-2023  润新知