Docker容器之间的通信

目录

一、容器之间添加链接
    方式一:--link参数
    方式二:创建一个网络
二、多容器复杂应用的部署
三、多机器通信
    Mutil-host networking with etcd
    setup etcd cluster
    重启docker服务
    创建overlay network
    创建连接demo网络的容器

一、容器之间添加链接

方式一:--link参数

用法:

[root@docker ~]# docker run -d --name test5 --link test1 cgy/mycentos:v2 /bin/bash -c "while true;do sleep 3600;done"
82a256cf2c4c7dee27129e8c2aafcace4e9a30940150e16eb008ad7a139cd96f

解析: --link test1 test1是一个已存在并运行着的容器,--link的作用就相当于在容器test5的/etc/hosts中添加了一条容器名与ip的映射关系。以后test5容器就可以直接使用容器名与test1进行通信了。

验证:

[root@docker ~]# docker exec -it test5 ping test1
PING test1 (172.17.0.4) 56(84) bytes of data.
64 bytes from test1 (172.17.0.4): icmp_seq=1 ttl=64 time=0.065 ms
64 bytes from test1 (172.17.0.4): icmp_seq=2 ttl=64 time=0.089 ms
^C
--- test1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.065/0.077/0.089/0.012 ms

方式二:创建一个网络

  1. 自己创建一个网络
[root@docker ~]# docker network create -d bridge my-bridge
01f3d92281d7dd6eaeabd77c95c62f0d33f8d45bd0e1bc7c7e1c3208526dfd2a

创建一个网络,-d bridge网络驱动器为bridge,名称叫mybridge

查看已创建的网络:


Docker容器之间的通信_第1张图片
image.png

2, 启动一个容器,使用自建的网络my-bridge

[root@docker ~]# docker run -d --name test3 --network my-bridge cgy/mycentos:v2 /bin/bash -c "while true;do sleep 3600;done"

44d549f38e2a38d528d26193c5585f8c68008411d764ad39d23dc57ee48ab28c

--network my-bridge:指定容器使用的网络为自建的my-bridge.

使用自建网络启动的容器,ip 为172.18.0.2


Docker容器之间的通信_第2张图片
image.png

再启动一个容器test4,不使用--network指定网络,默认使用docker0网络:

[root@docker ~]# docker run -d --name test4  cgy/mycentos:v2 /bin/bash -c "while true;do sleep 3600;done"
c64c2993e94a3dc0359a0e38ed5f5d262c0b01be45bacdf1788c7b0c2223777b

容器test3和test4没做关联时,不管是使用容器名还是容器的IP,都是无法ping通的:


Docker容器之间的通信_第3张图片
image.png
  1. 将test4也加入自建的my-bridge
[root@docker ~]# docker network connect my-bridge test4

用法:Usage: docker network connect [OPTIONS] NETWORK CONTAINER

查看test4就多了一个虚拟网卡,并和test3在同一网段


Docker容器之间的通信_第4张图片
image.png
  1. 这时就可以直接使用容器名去通信了


    Docker容器之间的通信_第5张图片
    image.png
  1. 再查看一下my-bridge的详细信息
[root@docker ~]# docker network inspect my-bridge
[
    {
        "Name": "my-bridge",
        "Id": "01f3d92281d7dd6eaeabd77c95c62f0d33f8d45bd0e1bc7c7e1c3208526dfd2a",
        "Created": "2018-05-01T01:08:04.864178764+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "44d549f38e2a38d528d26193c5585f8c68008411d764ad39d23dc57ee48ab28c": {
                "Name": "test3",
                "EndpointID": "95f13c730e08f7c82e5f3ec555f3c3afa79a50eceb7a1f540463ba181c81d05c",
                "MacAddress": "02:42:ac:12:00:02",
                "IPv4Address": "172.18.0.2/16",
                "IPv6Address": ""
            },
            "c64c2993e94a3dc0359a0e38ed5f5d262c0b01be45bacdf1788c7b0c2223777b": {
                "Name": "test4",
                "EndpointID": "9b41a9ef9b3e6dabdaad52167642a74aa7e05f93ceec65768b311945c8f2c036",
                "MacAddress": "02:42:ac:12:00:03",
                "IPv4Address": "172.18.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

可以看到,my-bridge已经连接了两个容器test3和test4。

二、多容器复杂应用的部署

接下来部署一个flask程序,程序中需要用到redis。所以要启动两个容器,分别是运行redis服务的容器和运行flask程序的容器,而flask容器需要依赖redis容器。

先启动一个redis容器

[root@docker dockerfile]# docker run -d --name redis redis
52e9642a8decaf3ff4b6ba895c6e3ebaeaf3b8625aa212c86285711d6bc904f1

redis只是程序内部使用的,所以不需要对外暴露端口。

构建一上flask程序的镜像

app.py文件内容:

from flask import Flask
from redis import Redis
import os
import socket

app = Flask(__name__)
redis = Redis(host=os.environ.get('REDIS_HOST', '127.0.0.1'), port=6379)

app.route('/')
def hello():
    redis.incr('hits')
    response = 'Hello Container World! I have been seen %s times and hostname is %s.\n' %(redis.get('hits'), socket.gethostname())
    return response

if __name__ == '__main__':
    app.run(port=6600,host="0.0.0.0")

通过获取环境变量的方式,去获得redis服务器的访问地址。容器启动时,需要--link redis关联redis容器,和-e REDIS_HOST=redis设置容器的环境变量。

Dockerfile文件内容:

FROM python:3.6
MAINTAINER "caiguangyin" "[email protected]"
RUN pip install flask redis
COPY app.py /app/
WORKDIR /app
CMD ["python","app.py"]

构建flask程序镜像:

[root@docker flask-redis]# docker build -t cgy/flask-redis:v2 .

启动容器,并在后台运行:

[root@docker flask-redis]# docker run -d --name flask-redis --link redis -e REDIS_HOST=redis -p 6600:6600 cgy/flask-redis:v2
d72d111077061bf644f5dbba8adabd5e2fc81fc7e778795ad7f0135c0f85cdaf

-e REDIS_HOST=redis:表示在容器中设置一个环境变量REDIS_HOST,值为redis。

进入容器查看:docker exec -it flask-redis /bin/bash

Docker容器之间的通信_第6张图片
image.png

访问:


Docker容器之间的通信_第7张图片
image.png

三、多机器通信

Docker容器之间的通信_第8张图片
image.png

Mutil-host networking with etcd

setup etcd cluster

在docker-node1上

vagrant@docker-node1:~$ wget https://github.com/coreos/etcd/releases/download/v3.0.12/etcd-v3.0.12-linux-amd64.tar.gz
vagrant@docker-node1:~$ tar zxvf etcd-v3.0.12-linux-amd64.tar.gz
vagrant@docker-node1:~$ cd etcd-v3.0.12-linux-amd64
vagrant@docker-node1:~$ nohup ./etcd --name docker-node1 --initial-advertise-peer-urls http://192.168.205.10:2380 \
--listen-peer-urls http://192.168.205.10:2380 \
--listen-client-urls http://192.168.205.10:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://192.168.205.10:2379 \
--initial-cluster-token etcd-cluster \
--initial-cluster docker-node1=http://192.168.205.10:2380,docker-node2=http://192.168.205.11:2380 \
--initial-cluster-state new&

在docker-node2上

vagrant@docker-node2:~$ wget https://github.com/coreos/etcd/releases/download/v3.0.12/etcd-v3.0.12-linux-amd64.tar.gz
vagrant@docker-node2:~$ tar zxvf etcd-v3.0.12-linux-amd64.tar.gz
vagrant@docker-node2:~$ cd etcd-v3.0.12-linux-amd64/
vagrant@docker-node2:~$ nohup ./etcd --name docker-node2 --initial-advertise-peer-urls http://192.168.205.11:2380 \
--listen-peer-urls http://192.168.205.11:2380 \
--listen-client-urls http://192.168.205.11:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://192.168.205.11:2379 \
--initial-cluster-token etcd-cluster \
--initial-cluster docker-node1=http://192.168.205.10:2380,docker-node2=http://192.168.205.11:2380 \
--initial-cluster-state new&

检查cluster状态

vagrant@docker-node2:~/etcd-v3.0.12-linux-amd64$ ./etcdctl cluster-health
member 21eca106efe4caee is healthy: got healthy result from http://192.168.205.10:2379
member 8614974c83d1cc6d is healthy: got healthy result from http://192.168.205.11:2379
cluster is healthy

重启docker服务

在docker-node1上

$ sudo service docker stop
$ sudo /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --cluster-store=etcd://192.168.205.10:2379 --cluster-advertise=192.168.205.10:2375&

在docker-node2上

$ sudo service docker stop
$ sudo /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --cluster-store=etcd://192.168.205.11:2379 --cluster-advertise=192.168.205.11:2375&

创建overlay network

在docker-node1上创建一个demo的overlay network

vagrant@docker-node1:~$ sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
0e7bef3f143a        bridge              bridge              local
a5c7daf62325        host                host                local
3198cae88ab4        none                null                local
vagrant@docker-node1:~$ sudo docker network create -d overlay demo
3d430f3338a2c3496e9edeccc880f0a7affa06522b4249497ef6c4cd6571eaa9
vagrant@docker-node1:~$ sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
0e7bef3f143a        bridge              bridge              local
3d430f3338a2        demo                overlay             global
a5c7daf62325        host                host                local
3198cae88ab4        none                null                local
vagrant@docker-node1:~$ sudo docker network inspect demo
[
    {
        "Name": "demo",
        "Id": "3d430f3338a2c3496e9edeccc880f0a7affa06522b4249497ef6c4cd6571eaa9",
        "Scope": "global",
        "Driver": "overlay",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "10.0.0.0/24",
                    "Gateway": "10.0.0.1/24"
                }
            ]
        },
        "Internal": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]

我们会看到在node2上,这个demo的overlay network会被同步创建

vagrant@docker-node2:~$ sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
c9947d4c3669        bridge              bridge              local
3d430f3338a2        demo                overlay             global
fa5168034de1        host                host                local
c2ca34abec2a        none                null                local

通过查看etcd的key-value, 我们获取到,这个demo的network是通过etcd从node1同步到node2的

vagrant@docker-node2:~/etcd-v3.0.12-linux-amd64$ ./etcdctl ls /docker
/docker/network
/docker/nodes
vagrant@docker-node2:~/etcd-v3.0.12-linux-amd64$ ./etcdctl ls /docker/nodes
/docker/nodes/192.168.205.11:2375
/docker/nodes/192.168.205.10:2375
vagrant@docker-node2:~/etcd-v3.0.12-linux-amd64$ ./etcdctl ls /docker/network/v1.0/network
/docker/network/v1.0/network/3d430f3338a2c3496e9edeccc880f0a7affa06522b4249497ef6c4cd6571eaa9
vagrant@docker-node2:~/etcd-v3.0.12-linux-amd64$ ./etcdctl get /docker/network/v1.0/network/3d430f3338a2c3496e9edeccc880f0a7affa06522b4249497ef6c4cd6571eaa9 | jq .
{
  "addrSpace": "GlobalDefault",
  "enableIPv6": false,
  "generic": {
    "com.docker.network.enable_ipv6": false,
    "com.docker.network.generic": {}
  },
  "id": "3d430f3338a2c3496e9edeccc880f0a7affa06522b4249497ef6c4cd6571eaa9",
  "inDelete": false,
  "ingress": false,
  "internal": false,
  "ipamOptions": {},
  "ipamType": "default",
  "ipamV4Config": "[{\"PreferredPool\":\"\",\"SubPool\":\"\",\"Gateway\":\"\",\"AuxAddresses\":null}]",
  "ipamV4Info": "[{\"IPAMData\":\"{\\\"AddressSpace\\\":\\\"GlobalDefault\\\",\\\"Gateway\\\":\\\"10.0.0.1/24\\\",\\\"Pool\\\":\\\"10.0.0.0/24\\\"}\",\"PoolID\":\"GlobalDefault/10.0.0.0/24\"}]",
  "labels": {},
  "name": "demo",
  "networkType": "overlay",
  "persist": true,
  "postIPv6": false,
  "scope": "global"
}

创建连接demo网络的容器

在docker-node1上

vagrant@docker-node1:~$ sudo docker run -d --name test1 --net demo busybox sh -c "while true; do sleep 3600; done"
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
56bec22e3559: Pull complete
Digest: sha256:29f5d56d12684887bdfa50dcd29fc31eea4aaf4ad3bec43daf19026a7ce69912
Status: Downloaded newer image for busybox:latest
a95a9466331dd9305f9f3c30e7330b5a41aae64afda78f038fc9e04900fcac54
vagrant@docker-node1:~$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
a95a9466331d        busybox             "sh -c 'while true; d"   4 seconds ago       Up 3 seconds                            test1
vagrant@docker-node1:~$ sudo docker exec test1 ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:0A:00:00:02
          inet addr:10.0.0.2  Bcast:0.0.0.0  Mask:255.255.255.0
          inet6 addr: fe80::42:aff:fe00:2/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:15 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1206 (1.1 KiB)  TX bytes:648 (648.0 B)

eth1      Link encap:Ethernet  HWaddr 02:42:AC:12:00:02
          inet addr:172.18.0.2  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:acff:fe12:2/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:648 (648.0 B)  TX bytes:648 (648.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

vagrant@docker-node1:~$

在docker-node2上

vagrant@docker-node2:~$ sudo docker run -d --name test1 --net demo busybox sh -c "while true; do sleep 3600; done"
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
56bec22e3559: Pull complete
Digest: sha256:29f5d56d12684887bdfa50dcd29fc31eea4aaf4ad3bec43daf19026a7ce69912
Status: Downloaded newer image for busybox:latest
fad6dc6538a85d3dcc958e8ed7b1ec3810feee3e454c1d3f4e53ba25429b290b
docker: Error response from daemon: service endpoint with name test1 already exists.
vagrant@docker-node2:~$ sudo docker run -d --name test2 --net demo busybox sh -c "while true; do sleep 3600; done"
9d494a2f66a69e6b861961d0c6af2446265bec9b1d273d7e70d0e46eb2e98d20

验证连通性。

vagrant@docker-node2:~$ sudo docker exec -it test2 ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:0A:00:00:03
          inet addr:10.0.0.3  Bcast:0.0.0.0  Mask:255.255.255.0
          inet6 addr: fe80::42:aff:fe00:3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1450  Metric:1
          RX packets:208 errors:0 dropped:0 overruns:0 frame:0
          TX packets:201 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:20008 (19.5 KiB)  TX bytes:19450 (18.9 KiB)

eth1      Link encap:Ethernet  HWaddr 02:42:AC:12:00:02
          inet addr:172.18.0.2  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:acff:fe12:2/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:648 (648.0 B)  TX bytes:648 (648.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

  vagrant@docker-node1:~$ sudo docker exec test1 sh -c "ping 10.0.0.3"
  PING 10.0.0.3 (10.0.0.3): 56 data bytes
  64 bytes from 10.0.0.3: seq=0 ttl=64 time=0.579 ms
  64 bytes from 10.0.0.3: seq=1 ttl=64 time=0.411 ms
  64 bytes from 10.0.0.3: seq=2 ttl=64 time=0.483 ms
  ^C
  vagrant@docker-node1:~$

你可能感兴趣的:(Docker容器之间的通信)