Dockerで起動したUbuntuコンテナからarchive.ubuntu.comの名前解決ができない場合の対処方法

Dockerで起動したUbuntuのコンテナで、apt-getを実行したところ以下のようなエラーが発生した。

$ apt-get install software-properties-common
・
・
・
0% [Connecting to archive.ubuntu.com]

Err http://archive.ubuntu.com/ubuntu/ trusty/main libroken18-heimdal amd64 1.6~git20131207+dfsg-1ubuntu1
  Could not resolve 'archive.ubuntu.com'

自分自身にPingを打ったところ届くので、hostの名前解決が出来てないようだった。

$ ping -w3 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.028 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.031 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.042 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.047 ms

--- 172.17.0.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2998ms
rtt min/avg/max/mdev = 0.028/0.037/0.047/0.007 ms

/etc/resolv.confをみてみると設定は以下のようになっていたので、nameserverの向先をGoogleのPublic DNS(8.8.8.8)に変える。

$ cat /etc/resolv.conf
nameserver 192.168.1.1
nameserver 192.168.1.228
nameserver 192.168.1.213

DNSサーバを変更するには、コンテナ作成時に--dnsオプションをつける必要がある。

$ docker run -i -t --name=test --dns=8.8.8.8 ubuntu /bin/bash

作成したコンテナの/etc/resolv.confをみてみると、DNSサーバは--dnsで指定したIPとなっている。

$ cat /etc/resolv.conf
nameserver 8.8.8.8

この状態でもう一度apt-getを試すと上手くいった。