Docker25:自定义网络(推荐)

Docker25:自定义网络(推荐)

Created
Nov 18, 2021 12:30 AM
Last Edited
Last updated April 14, 2022
Tags

1. 前言

查看所有网络
# 查看所有的docker网络 root@docker:/home/henggao/Desktop# docker network ls NETWORK ID NAME DRIVER SCOPE bca0a8305f26 bridge bridge local 9d5d46f3b050 host host local 591d8f64be59 none null local 5d91f2e85a2b somenetwork bridge local root@docker:/home/henggao/Desktop#
docker中的网络模式有:
  • bridge:桥接(docker默认)
  • none:不配置网络
  • host:和宿主机共享网络
 
docker run 命令默认带有一个参数–net bridge,此处的bridge指的就是docker0。如果我们不想使用docker0,那如何创建一个新的网络呢?

2. 自定义网络

# 自定义网络 docker network create --driver 网络模式 --subnet 子网ip --gateway 网关 网络名 root@docker:/home/henggao/Desktop# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet adc9329dead31516049861937f0e8369687f417323803028f3c87c0ed8a1c43d # 查看新创建的网络mynet root@docker:/home/henggao/Desktop# docker network ls NETWORK ID NAME DRIVER SCOPE bca0a8305f26 bridge bridge local 9d5d46f3b050 host host local adc9329dead3 mynet bridge local 591d8f64be59 none null local 5d91f2e85a2b somenetwork bridge local
 
我们不仅在docker network ls命令下发现了这个新创建的网络newnet,还可以使用docker network inspect命令查看其详细信息,包括了我们创建时定义的子网ip和网关:
notion image
 

3. 将Tomcat发布到自定义网路

只要两个容器启动时都通过 –net,选用了同一个已创建的网络,不同容器间即可通过ip地址或容器名/id连通
# 使用自定义网络启动容器1 root@docker:/home/henggao/Desktop# docker run -d -P --name tomcat-net-01 --net mynet tomcat 3ce09d02d365908877c7fa4eb61bdda1a4d5728fc98e7141212761ae75d9244a # 启动容器2 root@docker:/home/henggao/Desktop# docker run -d -P --name tomcat-net-02 --net mynet tomcat 613966b97e688f4b2b0a69dfcc193b9a3c80be96def9f0114905737c404a58e1 # 查看网络 root@docker:/home/henggao/Desktop# docker network inspect mynet [ { "Name": "mynet", "Id": "adc9329dead31516049861937f0e8369687f417323803028f3c87c0ed8a1c43d", "Created": "2021-11-18T10:37:14.723178178+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": {}, "Config": [ { "Subnet": "192.168.0.0/16", "Gateway": "192.168.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "3ce09d02d365908877c7fa4eb61bdda1a4d5728fc98e7141212761ae75d9244a": { "Name": "tomcat-net-01", "EndpointID": "42fe1b0234bfc74ee421a3896930238d524b55f203cdf9efb30b40fa9513233d", "MacAddress": "02:42:c0:a8:00:02", "IPv4Address": "192.168.0.2/16", "IPv6Address": "" }, "613966b97e688f4b2b0a69dfcc193b9a3c80be96def9f0114905737c404a58e1": { "Name": "tomcat-net-02", "EndpointID": "89d26dd1bce0fe25509f28c1022e50ba22aa05a3c6f9b368884628c97c5001e2", "MacAddress": "02:42:c0:a8:00:03", "IPv4Address": "192.168.0.3/16", "IPv6Address": "" } }, "Options": {}, "Labels": {} } ] root@docker:/home/henggao/Desktop#
 
可以通过容器名互相ping通。
推荐这样使用网路。
好处:
  • redis不同集群使用不同网络,保证集群健康、安全。