docker 容器互联

本文简单介绍两种, 一种 link, 另外一种 network

# 在终端A中, 创建容器 box1
# docker run -it --name box1 alpine:3.7

# 在终端B中, 创建容器 box2
# docker run -it --name box2 --link="box1:box1" alpine:3.7

# 在终端A里执行命令
# ping box2 -c 3
ping: bad address 'box2'

# 在终端B里执行命令
# ping box1 -c 3
PING box1 (172.17.0.2): 56 data bytes
64 bytes from 172.17.0.2: seq=0 ttl=64 time=0.089 ms
64 bytes from 172.17.0.2: seq=1 ttl=64 time=0.152 ms
64 bytes from 172.17.0.2: seq=2 ttl=64 time=0.160 ms
......

box2 能ping box1, box1 不能ping box2


network

# 新建名为 my-net 的网络 (-d 参数指定 Docker 网络类型, 有 bridge overlay)
# docker network create -d bridge my-net

# 在终端A中, 创建容器 box1
docker run -it --name box1 --network my-net alpine:3.7

# 在终端B中, 创建容器 box2
docker run -it --name box2 --network my-net alpine:3.7

# 在终端A里执行命令
# ping box2 -c 3
PING box2 (172.18.0.3): 56 data bytes
64 bytes from 172.18.0.3: seq=0 ttl=64 time=0.039 ms
64 bytes from 172.18.0.3: seq=1 ttl=64 time=0.167 ms
64 bytes from 172.18.0.3: seq=2 ttl=64 time=0.064 ms
......

# 在终端B里执行命令
# ping box1 -c 3
PING box1 (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.059 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.168 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.108 ms
......

容器 box1 与 容器 box2 建立了互联


注: 如果你有多个容器之间需要互相连接, 推荐使用 Docker Compose





猜你喜欢

转载自blog.csdn.net/gekkoou/article/details/80871507