ぶていのログでぶログ

思い出したが吉日

WSL上のDockerコンテナからarchive.ubuntu.comにアクセスできない問題を解決する

いきなり結論。WSLのIPレンジとDockerのIPレンジがバッティングしていた

$ ip a
-- snip --
6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:fc:7a:41 brd ff:ff:ff:ff:ff:ff
    inet 172.17.209.53/20 brd 172.17.223.255 scope global eth0 👈
-- snip --
7: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:34:64:61:fe brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0 👈
-- snip --

解決策としては/etc/docker/daemon.jsonを作って、バッティングしないIPレンジを設定する。 今回は172.23.0.1/16 にした*1

$ cat /etc/docker/daemon.json
{
  "bip": "172.23.0.1/16"
}

このファイルを作成するor編集したらdockerを再起動すると反映される。

$ sudo systemctl restart docker
❯ ip a
-- snip --
7: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:34:64:61:fe brd ff:ff:ff:ff:ff:ff
    inet 172.23.0.1/16 brd 172.23.255.255 scope global docker0 👈
-- snip --

archive.ubuntu.comに限らずWSL上のDockerコンテナからインターネットにつながらなくなったら確認するとよさそう。

おまけ: 原因の調査方法

ubuntuコンテナを使ってネットワークにつながらない原因を調査しようとしても、必要なコマンドが入っていない…。

$ docker run -it --rm ubuntu:latest
root@11960bcf46f3:/# ping 8.8.8.8
bash: ping: command not found
root@11960bcf46f3:/# dig google.com
bash: dig: command not found

これらのコマンドをインストールしようとしてもarchive.ubuntu.comにつながらないので詰みです…。 こういうときはbusyboxコンテナを使うといいらしい。

$ docker run -it --rm busybox
/ # ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=115 time=8.195 ms
64 bytes from 8.8.8.8: seq=1 ttl=115 time=7.584 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 7.584/7.889/8.195 ms
/ # nslookup google.com
Server:         172.17.208.1
Address:        172.17.208.1:53

Non-authoritative answer:
Name:   google.com
Address: 142.251.42.142

*** Can't find google.com: No answer

参考: SOLVED: Docker build “Could not resolve ‘archive.ubuntu.com’” apt-get fails to install anything | by Faithful Anere | Medium

*1:WSLがこのIPレンジを使わないかをちゃんと調べていないが、またバッティングしたら変えればいいか…っという気持ちになった