1、分别运行tomcat 和centos并指定名字
[root@localhost ~]# docker run -d --name web tomcat
c478d9fe2298485f367255dacd25b854a6162965b2108d6fe577bc082dc90595
[root@localhost ~]# docker run -d -it --name database centos /bin/bash
612ebdc56e2f0c1f763defadd3e6a2ed951a854c14e8ad9c24374df3ea709847
2、列出网络服务的明细,可以看到一个默认的网桥,但是我们不用它,我们自己创建一个网桥
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
06716cc472bf bridge bridge local
3、创建一个名为my-bridge的网桥,每创建一个网桥都会创建一个虚拟网卡(就是一个网关),
这样docker内部就可通过网桥来互连互通,但是要连接外网还得靠物理网卡。
[root@localhost ~]# docker network create -d bridge my-bridge
e402fee9f6d7297e85c820bb3543cb75c8791adf6b29ff84c879e24e39d6e2ee
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
e402fee9f6d7 my-bridge bridge local
4、用connect使web和database分别连接网桥
[root@localhost ~]# docker network connect my-bridge web
[root@localhost ~]# docker network connect my-bridge database
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
612ebdc56e2f centos "/bin/bash" 25 minutes ago Up 25 minutes database
c478d9fe2298 tomcat "catalina.sh run" 26 minutes ago Up 26 minutes 8080/tcp web
5、进入database拼web
[root@localhost ~]# docker exec -it 612ebdc56e2f /bin/bash
[root@612ebdc56e2f /]# ping web
PING web (172.18.0.2) 56(84) bytes of data.
64 bytes from web.my-bridge (172.18.0.2): icmp_seq=1 ttl=64 time=0.325 ms
--- web ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.076/0.200/0.325/0.125 ms
[root@612ebdc56e2f /]# exit
exit
6、进入web拼database
[root@localhost ~]# docker exec -it c478d9fe2298 /bin/bash
root@c478d9fe2298:/usr/local/tomcat# ping database
PING database (172.18.0.3) 56(84) bytes of data.
64 bytes from database.my-bridge (172.18.0.3): icmp_seq=1 ttl=64 time=0.135 ms
--- database ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1ms
rtt min/avg/max/mdev = 0.135/0.160/0.185/0.025 ms
root@c478d9fe2298:/usr/local/tomcat#