LoginSignup
81

More than 5 years have passed since last update.

Dockerで/etc/hostsファイルが操作出来ない対策

Last updated at Posted at 2014-05-15

追記 2015/08/17

現在はrun時に --add-host=[] オプションでホストを注入出来る。

docker run -t -i --add-host=test.example.co.jp:127.0.0.1 --add-host=test2.example.co.jp:127.0.0.1 test/hoge /bin/bash

dnsmasqとかもういらないので注意
バージョンが古くて使えない場合はdnsmasqで頑張ってください

長いことメンテナンスサボってすいません


コンテナの中の/etc/hostsはRead-Onlyのファイルになっており、決して操作出来ないため、hostsにドメインを追加したい時に困った

githubのissueにあった解決策を試す
ただしコンテナの環境がScientific Linuxだと、このままでは使えなかったため、userをrootに設定する
Cent OSでも同様の設定が有効

環境はCoreOSでコンテナがScientific Linux 6.4を使っている

Dockerfile
RUN yum -y install dnsmasq

# /etc/hosts values
RUN echo 'address="/test.example.co.jp/127.0.0.1"' >> /etc/dnsmasq.d/0hosts
RUN echo 'address="/test2.example.co.jp/127.0.0.1"' >> /etc/dnsmasq.d/0hosts
RUN echo 'address="/test3.example.co.jp/127.0.0.1"' >> /etc/dnsmasq.d/0hosts

# dnsmasq configuration
RUN echo 'listen-address=127.0.0.1' >> /etc/dnsmasq.conf
RUN echo 'resolv-file=/etc/resolv.dnsmasq.conf' >> /etc/dnsmasq.conf
RUN echo 'conf-dir=/etc/dnsmasq.d' >> /etc/dnsmasq.conf
RUN echo 'user=root' >> /etc/dnsmasq.conf

# dns setting
RUN echo 'nameserver 8.8.8.8' >> /etc/resolv.dnsmasq.conf
RUN echo 'nameserver 8.8.4.4' >> /etc/resolv.dnsmasq.conf
docker build -t test/dnsmasq .
docker run -t -i --dns 127.0.0.1 test/dnsmasq /bin/bash

これで名前解決できた
設定した上で、Dockerfileで設定してrunなりstartなりした時にdeamonをスタートさせたいんだけれど、今のところ方法がわからないので保留

追記

この記事大分ほったらかしにしていたが、今は --add-host オプションを使ってhostsに相当するものを編集できる
https://docs.docker.com/reference/run/#network-settings

つまりrun時に

docker run --add-host test.example.co.jp:127.0.0.1 --add-host test2.example.co.jp:127.0.0.1 -t -i test /bin/bash

なりをすれば良い。

runの時一々指定するのめんどいので、build時に設定したいって思って検索したら
https://github.com/docker/docker/issues/10324
http://jasonincode.com/customizing-hosts-file-in-docker/
が引っかかった

どうやらコミュニティ的には回避策があるので放置に向かう方向?(15/05/08時点)
としたらちょっと微妙。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
81