[Docker] ユーザ定義のブリッジネットワーク作成

デフォルトのブリッジネットワークとユーザ定義のブリッジネットワーク

ubuntuコンテナを起動して詳細を確認します
$ sudo docker run -itd –name ubuntu1 ubuntu /bin/bash

$ sudo docker inspect ubuntu1
L ipアドレスの箇所で 172.17.0.2 が割り当てられている

            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "9d63e39880cdedc5addbd10a11deb3fad9b4679dca150c8ab24c6080a777d0a5",
                    "EndpointID": "d990aa1ffeb44365cc97df34730bf143b2a0b0afbe461fe811b877fca9ad390f",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }

もう一つ同じようにコンテナを作成する
$ sudo docker run -itd –name ubuntu2 ubuntu /bin/bash
$ sudo docker inspect ubuntu2
L ipアドレスの箇所で 172.17.0.3 が割り当てられている

            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "9d63e39880cdedc5addbd10a11deb3fad9b4679dca150c8ab24c6080a777d0a5",
                    "EndpointID": "ea06868987306ff7b8f7419a287d4a8d7282914f2c9746afbe991d9d26e2d657",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }

$ sudo docker exec -ti 77573860f37e /bin/bash
$ apt-get update && apt install iputils-ping
root@77573860f37e:/# ping -c 3 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.079 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.064 ms
64 bytes from 172.17.0.3: icmp_seq=3 ttl=64 time=0.099 ms

— 172.17.0.3 ping statistics —
3 packets transmitted, 3 received, 0% packet loss, time 2027ms
rtt min/avg/max/mdev = 0.064/0.080/0.099/0.014 ms
root@77573860f37e:/# ping -c 3 ubuntu2
ping: ubuntu2: Name or service not known

### コンテナ名で名前解決する方法
$ sudo docker network create my_nw
$ sudo docker network connect my_nw ubuntu1
$ sudo docker network connect my_nw ubuntu2
$ sudo docker exec -ti 77573860f37e /bin/bash
root@77573860f37e:/# ping -c 3 ubuntu2
PING ubuntu2 (172.22.0.3) 56(84) bytes of data.
64 bytes from ubuntu2.my_nw (172.22.0.3): icmp_seq=1 ttl=64 time=0.141 ms
64 bytes from ubuntu2.my_nw (172.22.0.3): icmp_seq=2 ttl=64 time=0.083 ms
64 bytes from ubuntu2.my_nw (172.22.0.3): icmp_seq=3 ttl=64 time=0.068 ms

おおおおおおお

$ sudo docker network ls