跨主機間的 Docker overlay network (使用 etcd)

若要使不同主機間的 Docker 中的 container 能互相溝通 (讓他們在同個網路底下) 有幾種方式,陸續跟大家分享一下。

透過 etcd

早先在 swarm 還沒那麼完善時,透過 etcd 分散式的 key/value 儲存服務,儲存並同步各 Docker node 資訊,這是當時比較常見的做法。假設現在有兩個 Docker node,sx01sx02

hostname ip addr
sx01 10.1.1.70
sx02 10.1.1.71

我們先分別在 sx01, sx02 安裝 etcd

  • sx01
1
2
3
4
5
6
7
8
9
10
wget https://github.com/coreos/etcd/releases/download/v3.0.12/etcd-v3.0.12-linux-amd64.tar.gz
tar zxvf etcd-v3.0.12-linux-amd64.tar.gz
cd etcd-v3.0.12-linux-amd64
nohup ./etcd --name sx01 --initial-advertise-peer-urls http://10.1.1.70:2380 \
--listen-peer-urls http://10.1.1.70:2380 \
--listen-client-urls http://10.1.1.70:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://10.1.1.70:2379 \
--initial-cluster-token etcd-cluster \
--initial-cluster sx01=http://10.1.1.70:2380,sx02=http://10.1.1.71:2380 \
--initial-cluster-state new &
  • sx02
1
2
3
4
5
6
7
8
9
10
wget https://github.com/coreos/etcd/releases/download/v3.0.12/etcd-v3.0.12-linux-amd64.tar.gz
tar zxvf etcd-v3.0.12-linux-amd64.tar.gz
cd etcd-v3.0.12-linux-amd64
nohup ./etcd --name sx02 --initial-advertise-peer-urls http://10.1.1.71:2380 \
--listen-peer-urls http://10.1.1.71:2380 \
--listen-client-urls http://10.1.1.71:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://10.1.1.71:2379 \
--initial-cluster-token etcd-cluster \
--initial-cluster sx01=http://10.1.1.70:2380,sx02=http://10.1.1.71:2380 \
--initial-cluster-state new &

透過在 sx02 輸入 ./etcdctl cluster-health 我們可以確認 etcd 服務有正確啟動:

1
2
member 21eca106efe4caee is healthy: got healthy result from http://10.1.1.70:2379
member 8614974c83d1cc6d is healthy: got healthy result from http://10.1.1.71:2379

接著設定 dockerd 讓它在啟動時能夠與 etcd 服務連接,藉此與其他 Docker 同步網路資訊與容器狀態:

1
systemctl edit docker

會自動開啟編輯器,在當中填入

  • sx01
1
2
3
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --cluster-store=etcd://10.1.1.70:2379 --cluster-advertise=10.1.1.70:2375
  • sx02
1
2
3
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --cluster-store=etcd://10.1.1.71:2379 --cluster-advertise=10.1.1.71:2375

接著將各自的 Docker 服務重啟

1
systemctl restart docker

這時我們嘗試在 sx01 建立一個名為 test_net 的 overlay 網路:

1
docker network create -d overlay test_net

同時在 sx02 我們可以發現 test_net 也已自動出現:

1
2
3
4
5
6
# docker network ls
NETWORK ID NAME DRIVER SCOPE
c9947d4c3669 bridge bridge local
3d430f3338a2 test_net overlay global
fa5168034de1 host host local
c2ca34abec2a none null local

再來只要我們在任意 Docker node 執行 container 時加上 --net test_net 參數,即可為 container 增加一互相連通的網路介面 (eth1)。

References