运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

Docker学习之“docker network”

运维开发网 https://www.qedev.com 2020-09-28 13:21 出处:51CTO 作者:冰润冷曦
Docker网络基础"dockernetwork"命令$dockernetworkUsage:dockernetworkCOMMANDManagenetworksCommands:connectConnectacontainertoanetworkcreateCreateanetworkdisconnectDisconnectacontainerfromanetworkinsp

Docker网络基础

"docker network"命令

$ docker network

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 network”命令的用法:

  • connect : 连接容器到一个网络
  • create : 建立一个新网络
  • disconnect : 将容器从一个网络断开
  • inspect : 显示一个或多个网络的详细信息
  • ls : 显示网络
  • prune : 移除所有未使用的网络
  • rm : 移除一个或多个网络

可以在“docker network COMMAND”子命令后加“--help”来获取命令使用帮助。


“docker network ls”列表当前网络

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
928693f77827          bridge                 bridge                   local
ca44c117c782          host                    host                      local
4b5aef0c6228          none                   null                       local

以上输出的内容为docker安装后自动生成的网络,新建的网络在使用“docker network ls”后也将在这里显示。


“docker network inspect”显示网络的详细信息

$ docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "928693f7782710ca7aac317a355d0680f65e0326ba343519f4b914e946170dab",
        "Created": "2020-09-23T10:14:45.07052746+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": {},
        "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": {}
    }
]

“docker info”显示关于docker的插件信息

$ docker info
Client:
 Debug Mode: false

Server:
 Containers: 3
  Running: 0
  Paused: 0
  Stopped: 3
 Images: 24
 Server Version: 19.03.13
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 8fba4e9a7d01810a393d5d25a3621dc101981175
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.4.0-47-generic
 Operating System: Ubuntu 20.04.1 LTS
 OSType: Linux
 Architecture: x86_64
 CPUs: 2
 Total Memory: 3.817GiB
 Name: ubuntu-Virtual-machine
 ID: BSQN:3DPM:DO32:N3US:SO33:LDAD:OXGX:GR23:RQS4:NROX:5SEF:3J26
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No swap limit support

摘自“https://github.com/docker/labs/blob/master/networking/A1-network-basics.md#docker-networking-basics”


桥接网络

安装“brctl”命令并用它来在docker主机上列出Linux桥接网络

$ apt-get install bridge-utils
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libfprint-2-tod1 Linux-headers-5.4.0-45 Linux-headers-5.4.0-45-generic Linux-image-5.4.0-45-generic Linux-modules-5.4.0-45-generic
  Linux-modules-extra-5.4.0-45-generic
Use 'apt autoremove' to remove them.
Suggested packages:
  ifupdown
The following NEW packages will be installed:
  bridge-utils
0 upgraded, 1 newly installed, 0 to remove and 16 not upgraded.
Need to get 30.5 kB of archives.
After this operation, 112 kB of additional disk space will be used.
Get:1 http://cn.archive.ubuntu.com/ubuntu focal/main amd64 bridge-utils amd64 1.6-2ubuntu1 [30.5 kB]
Fetched 30.5 kB in 11s (2,824 B/s)
Selecting previously unselected package bridge-utils.
(Reading database ... 235697 files and directories currently installed.)
Preparing to unpack .../bridge-utils_1.6-2ubuntu1_amd64.deb ...
Unpacking bridge-utils (1.6-2ubuntu1) ...
Setting up bridge-utils (1.6-2ubuntu1) ...
Processing triggers for man-db (2.9.1-1) ...

$  brctl show
bridge name     bridge id               STP enabled     interfaces
docker0         8000.0242f94722ea       no

上述“brctl show”命令输出中可以看到“docker0”网络,这是docker安装时自动建立的桥接网络,其上没有端口连接。

可以使用“ip a”命令查看端口详细信息:

$ ip a
docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:f9:47:22:ea brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:f9ff:fe47:22ea/64 scope link
       valid_lft forever preferred_lft forever

运行一个容器:

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
542c40d3e039        debian:latest       "/bin/bash"         6 days ago          Up About a minute                       debian

再检查桥接网格:

$ brctl show
bridge name     bridge id               STP enabled     interfaces
docker0         8000.0242f94722ea       no              veth24101fe

$ docker network inspect bridge
<Snip>
"ConfigOnly": false,
        "Containers": {
            "542c40d3e0395f0efbe4fa4ab2bdd4c7503d1ced64f72dfc3f1a01cc0de22024": {
                "Name": "debian",
                "EndpointID": "07d107d83158960a43e380efccf3987ba696d131d7b4f8a5645b16f31fc2ca5e",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
<Snip>

测试网络连接:

$ 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.203 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.115 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.121 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.198 ms
64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.112 ms
64 bytes from 172.17.0.2: icmp_seq=6 ttl=64 time=0.109 ms
^C
--- 172.17.0.2 ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5108ms
rtt min/avg/max/mdev = 0.109/0.143/0.203/0.040 ms

进入容器并安装“ping”命令,然后测试外网连接:

$ apt-get install -y iputils-ping
Reading package lists... Done
Building dependency tree
Reading state information... Done
iputils-ping is already the newest version (3:20180629-2+deb10u1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

$ ping www.163.com
PING z163ipv6.v.bsgslb.cn (60.163.162.49) 56(84) bytes of data.
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=1 ttl=127 time=11.2 ms
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=2 ttl=127 time=10.5 ms
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=3 ttl=127 time=11.8 ms
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=4 ttl=127 time=15.0 ms
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=5 ttl=127 time=10.7 ms
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=6 ttl=127 time=10.1 ms
64 bytes from 49.162.163.60.broad.jx.zj.dynamic.163data.com.cn (60.163.162.49): icmp_seq=7 ttl=127 time=12.9 ms
^C
--- z163ipv6.v.bsgslb.cn ping statistics ---
7 packets transmitted, 7 received, 0% packet loss, time 19ms
rtt min/avg/max/mdev = 10.068/11.737/15.017/1.600 ms

为外部连接配置NAT:

$ docker run -itd --name nginx -p 8080:80 nginx
bf095588cd2685e44f69f4e6e0d0200c315af0e5d888b0585c3ac606719a5e37
$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
bf095588cd26        nginx               "/docker-entrypoint.…"   6 seconds ago       Up 5 seconds        0.0.0.0:8080->80/tcp   nginx

Docker学习之“docker network”

或者通过“crul”命令测试:

$ curl 127.0.0.1:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

摘自“https://github.com/docker/labs/blob/master/networking/A2-bridge-networking.md”


覆盖网络及发现服务

创建新的集群“docker swarm init”

$  docker swarm init
Swarm initialized: current node (dl3pk9a0nb1fruo6oj12wvd90) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-08ri50pd0eoxbeg9yafbquyv28w88yugvivw4g8gs7ww0vp2fo-02xnfu72xszdmx987oh7f7p9l 192.168.144.128:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

将节点添加至集群“docker swarm join”

$ docker swarm join --token SWMTKN-1-08ri50pd0eoxbeg9yafbquyv28w88yugvivw4g8gs7ww0vp2fo-02xnfu72xszdmx987oh7f7p9l 192.168.144.128:2377
This node joined a swarm as a worker.

查看当前集群中的节点“docker node ls”

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
617vb1qu809pdgnlhxccjgg8j     centos              Ready               Active                                  19.03.13
dl3pk9a0nb1fruo6oj12wvd90 *   ubuntu              Ready               Active              Leader              19.03.13

创建overlay网络“docker network create -d overlay overnet”

$ docker network create -d overlay overnet
z5t9zpxkatdfnjcut8vh4bjw9

创建overlay网络时,会自动创建名为“docker_gwbridge”和“ingress”的网络。

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f324866e5c73        bridge              bridge              local
99eceb22848e        docker_gwbridge     bridge              local
ca44c117c782        host                host                local
ioqiuda17gqw        ingress             overlay             swarm
4b5aef0c6228        none                null                local
z5t9zpxkatdf        overnet             overlay             swarm
cac68cc024d3        ubuntu-centos       bridge              local

在worker(centos)机器上运行“docker network ls”,网络显示如下:

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
dd908452957a        bridge              bridge              local
b0bcda8402ff        docker_gwbridge     bridge              local
d2efba80311a        host                host                local
ioqiuda17gqw        ingress             overlay             swarm
8b2162d44ebf        none                null                local
注意,“overnet”网络没有出现在列表中。这是因为Docker只在需要时扩展覆盖网络到主机。通常是当主机从网络上创建的服务运行任务时。

查看overnet网络详情“docker network inspect overnet”

$ docker network inspect overnet
[
    {
        "Name": "overnet",
        "Id": "z5t9zpxkatdfnjcut8vh4bjw9",
        "Created": "2020-09-24T00:27:19.936569293Z",
        "Scope": "swarm",
        "Driver": "overlay",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "10.0.1.0/24",
                    "Gateway": "10.0.1.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": null,
        "Options": {
            "com.docker.network.driver.overlay.vxlanid_list": "4097"
        },
        "Labels": null
    }
]

创建一个服务

$ docker service create --name myservice \
> --network overnet \
> --replicas 2 \
> ubuntu sleep infinity
9raa20nrm00nz57ppcfjtdvaw
overall progress: 2 out of 2 tasks
1/2: running   [==================================================>]
2/2: running   [==================================================>]
verify: Service converged
$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
9raa20nrm00n        myservice           replicated          2/2                 ubuntu:latest

REPLICAS项标明2个服务均已启动并正常运行。

$ docker service ps myservice
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
xr2kpd85iiui        myservice.1         ubuntu:latest       ubuntu              Running             Running 3 minutes ago
apihkr00g19i        myservice.2         ubuntu:latest       centos              Running             Running 3 minutes ago

在worker(centos)上检查网络情况,可以看到“overnet”网络了。

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
dd908452957a        bridge              bridge              local
b0bcda8402ff        docker_gwbridge     bridge              local
d2efba80311a        host                host                local
ioqiuda17gqw        ingress             overlay             swarm
8b2162d44ebf        none                null                local
z5t9zpxkatdf        overnet             overlay             swarm

查看网络详情,可以看到容器的IP为“10.0.1.4/24”:

$ docker network inspect overnet
<Snip>
        "ConfigOnly": false,
        "Containers": {
            "93575aabbefd06698e1d26a2e0c7b1143d18928c1875841a496af20d72bfd64f": {
                "Name": "myservice.2.apihkr00g19iy7l7wckqumaha",
                "EndpointID": "ed60bc66748221dfa57e704009dd89d96c896c94dcb3b9df9f5ce862ad79b82a",
                "MacAddress": "02:42:0a:00:01:04",
                "IPv4Address": "10.0.1.4/24",
                "IPv6Address": ""
<Snip>

在manager(ubuntu)上查看网络详细,可以看到容器的IP为“10.0.1.3/24”:

$ docker network inspect overnet
<Snip>
        "ConfigOnly": false,
        "Containers": {
            "a6d6351846e380f523339bbb80338d3239037d9a773534bb1491f06186fe4a70": {
                "Name": "myservice.1.xr2kpd85iiuinl4dqw32ikqgm",
                "EndpointID": "7a1e3a40f284e9db9558d707e01d53032244fd5e1c4aaccf93b60ac5a719daef",
                "MacAddress": "02:42:0a:00:01:03",
                "IPv4Address": "10.0.1.3/24",
                "IPv6Address": ""
<Snip>

登入容器并测试网络

$ apt-get update && apt-get install iputils-ping
<Snip>
$ ping 10.0.1.3
PING 10.0.1.3 (10.0.1.3) 56(84) bytes of data.
64 bytes from 10.0.1.3: icmp_seq=1 ttl=64 time=1.01 ms
64 bytes from 10.0.1.3: icmp_seq=2 ttl=64 time=0.971 ms
64 bytes from 10.0.1.3: icmp_seq=3 ttl=64 time=0.948 ms
64 bytes from 10.0.1.3: icmp_seq=4 ttl=64 time=1.01 ms
64 bytes from 10.0.1.3: icmp_seq=5 ttl=64 time=0.963 ms
64 bytes from 10.0.1.3: icmp_seq=6 ttl=64 time=1.05 ms
^C
--- 10.0.1.3 ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5008ms
rtt min/avg/max/mdev = 0.948/0.991/1.051/0.034 ms
$ apt-get update && apt-get install iputils-ping
<Snip>
$ ping 10.0.1.4
PING 10.0.1.4 (10.0.1.4) 56(84) bytes of data.
64 bytes from 10.0.1.4: icmp_seq=1 ttl=64 time=1.00 ms
64 bytes from 10.0.1.4: icmp_seq=2 ttl=64 time=1.11 ms
64 bytes from 10.0.1.4: icmp_seq=3 ttl=64 time=1.07 ms
64 bytes from 10.0.1.4: icmp_seq=4 ttl=64 time=1.02 ms
64 bytes from 10.0.1.4: icmp_seq=5 ttl=64 time=1.25 ms
64 bytes from 10.0.1.4: icmp_seq=6 ttl=64 time=1.18 ms
^C
--- 10.0.1.4 ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5009ms
rtt min/avg/max/mdev = 1.004/1.106/1.252/0.086 ms

测试发现服务

检查DNS配置文件
$ cat /etc/resolv.conf
search localdomain
nameserver 127.0.0.11
options ndots:0

可以发现容器的DNS解析均使用“nameserver 127.0.0.11”这个本地地址,监听端口:53。

$ ping myservice
PING myservice (10.0.1.2) 56(84) bytes of data.
64 bytes from 10.0.1.2: icmp_seq=1 ttl=64 time=0.109 ms
64 bytes from 10.0.1.2: icmp_seq=2 ttl=64 time=0.131 ms
^C
--- myservice ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 10007ms
rtt min/avg/max/mdev = 0.109/0.120/0.131/0.011 ms
退出容器并检查其虚拟IP
$ docker service inspect myservice
<Snip>
            "VirtualIPs": [
                {
                    "NetworkID": "6jb9uppj2ve5ix27x1myy1oqb",
                    "Addr": "10.0.1.2/24"
                }
            ]
<Snip>

摘自“https://github.com/docker/labs/blob/master/networking/A3-overlay-networking.md”

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号