原文地址,转载请注明出处:http://blog.csdn.net/qq_34021712/article/details/75948566 ©王赛超
之前使用pipework 分配静态ip是暂时的,重启之后就会失效,并且使用pipework绑定的ip 物理机,虚拟机,docker容器的ip都在同一网段,这在生产环境是很困难的,下面使用docker自带的network实现固定ip分配,并且重启不会消失。
服务器IP | 容器分配网段 | 启动容器的ID |
192.168.1.105 | 172.172.0.0/24 | 172.172.0.10 |
192.168.1.106 | 172.172.1.0/24 | 172.172.1.10 |
先操作192.168.1.105虚拟机
第一步:创建自定义网络
docker network create --subnet=172.172.0.0/24 docker-br0
备注:这里选取了172.172.0.0网段,也可以指定其他任意空闲的网段,docker-br0为自定义网桥的名字,可自己任意取名。第二步:在你自定义的网段选取任意IP地址作为你要启动容器IP
docker run -i -d --net docker-br0 --ip 172.172.0.10 --name nginx -v /usr/local/software/:/mnt/software/ 3bee3060bfc8 /bin/bash
备注:创建容器时,在第一步创建的网段中选取了172.172.0.10作为静态IP地址。并且以docker-br0网桥启动. -v是挂载,表示需要将本地哪个目录挂载到容器中。3bee3060bfc8是镜像ID第三步:测试本机和容器是否ping通
#测试ping 百度
[root@e98109ef9fd6 /]# ping www.baidu.com
PING www.a.shifen.com (119.75.213.61) 56(84) bytes of data.
64 bytes from 119.75.213.61 (119.75.213.61): icmp_seq=1 ttl=56 time=10.1 ms
64 bytes from 119.75.213.61 (119.75.213.61): icmp_seq=2 ttl=56 time=8.26 ms
#测试宿主机
[root@e98109ef9fd6 /]# ping 192.168.1.105
PING 192.168.1.105 (192.168.1.105) 56(84) bytes of data.
64 bytes from 192.168.1.105: icmp_seq=1 ttl=64 time=0.099 ms
64 bytes from 192.168.1.105: icmp_seq=2 ttl=64 time=0.081 ms
#测试ping另一台虚拟机
[root@e98109ef9fd6 /]# ping 192.168.1.106
PING 192.168.1.106 (192.168.1.106) 56(84) bytes of data.
64 bytes from 192.168.1.106: icmp_seq=1 ttl=63 time=1.67 ms
64 bytes from 192.168.1.106: icmp_seq=2 ttl=63 time=0.587 ms
到此给容器绑定固定ip 已完成,下面是 容器跨主机互相访问。
[root@e98109ef9fd6 /]# ping 172.172.1.10
PING 172.172.1.10 (172.172.1.10) 56(84) bytes of data.
From 192.168.1.105 icmp_seq=1 Destination Host Unreachable
From 192.168.1.105 icmp_seq=2 Destination Host Unreachable
From 192.168.1.105 icmp_seq=3 Destination Host Unreachable
[root@e98109ef9fd6 /]# ping 172.172.0.10
PING 172.172.0.10 (172.172.0.10) 56(84) bytes of data.
From 192.168.1.106 icmp_seq=1 Destination Host Unreachable
From 192.168.1.106 icmp_seq=2 Destination Host Unreachable
From 192.168.1.106 icmp_seq=3 Destination Host Unreachable
第六步:配置路由表
#添加路由规则[root@e98109ef9fd6 /]# ping 172.172.1.10
PING 172.172.1.10 (172.172.1.10) 56(84) bytes of data.
64 bytes from 172.172.1.10: icmp_seq=1 ttl=62 time=0.636 ms
64 bytes from 172.172.1.10: icmp_seq=2 ttl=62 time=0.411 ms
64 bytes from 172.172.1.10: icmp_seq=3 ttl=62 time=0.472 ms
[root@8343ad7e7f0f /]# ping 172.172.0.10
PING 172.172.0.10 (172.172.0.10) 56(84) bytes of data.
64 bytes from 172.172.0.10: icmp_seq=1 ttl=62 time=0.920 ms
64 bytes from 172.172.0.10: icmp_seq=2 ttl=62 time=0.674 ms
64 bytes from 172.172.0.10: icmp_seq=3 ttl=62 time=0.657 ms