# Dockerfile 的 /etc/hosts 如何設定

來源：

[Dockerfile 的 /etc/hosts 如何設定 – Tsung's Blog (longwin.com.tw)](https://blog.longwin.com.tw/2018/09/docker-dockerfile-etc-hosts-dns-setup-2018/)

## Dockerfile 的 /etc/hosts 如何設定

於 [Dockerfile reference](https://docs.docker.com/engine/reference/builder/) 文件裡面，沒有看到 /etc/hosts 該怎麼改，後來發現 /etc/hosts 修改的方式還蠻黑暗的~

修改 /etc/hosts 的作法有兩種，先講比較正確的方法：

Docker 增加 hosts 可以參考 Docker run 的文件：[Docker run reference](https://docs.docker.com/engine/reference/run/)

於 Docker run 使用 --add-host=server-name:127.0.0.1，多個用空白隔開，繼續寫下去即可，範例如下：

- **docker run ... --add-host='server:0.0.0.0' ...**
- **docker run ... --add-host='server:127.0.0.1' --add-host='server2:127.0.0.2'...**

若有 /etc/hosts 有太多需要增加，可以使用下述 Shell script 產生 --add-host 參數

- /etc/hosts 若要 1 vs 1 的 ip host 對應 
    - **cat /etc/hosts | sed 's/^#.\*//g' | grep '\[0-9\]\[0-9\]' | tr "\\t" " " | awk '{print "--add-host="$2":"$1 }' | tr '\\n' ' '**
- /etc/hosts 若要 1 vs n(多) 的 ip host 對應 
    - **cat /etc/hosts | grep -v "^#" | awk '{for(i=2;i&lt;=NF;i++){print "--add-host "$i":"$1}}'**

再來看比較暴力的作法：(直接寫在 Dockerfile 裡面)

```
# 使用 /tmp/hosts 當 /etc/hosts COPY /etc/hosts /tmp/hosts.bak
RUN cp hosts /tmp/hosts # hosts 於外部 cp /etc/hosts .
#RUN cp /etc/hosts /tmp/hosts #路径长度最好保持一致
RUN mkdir -p -- /lib-override && cp /lib/x86_64-linux-gnu/libnss_files.so.2 /lib-override
RUN sed -i 's:/etc/hosts:/tmp/hosts:g' /lib-override/libnss_files.so.2
ENV LD_LIBRARY_PATH /lib-override
RUN cat /tmp/hosts.bak >> /tmp/hosts
```

Docker 內部讀取 /etc/hosts 的部份，修改成讀取 **/tmp/hosts** (參考自此篇：[Docker 修改 hosts](https://wongxingjun.github.io/2016/04/06/Docker%E4%BF%AE%E6%94%B9hosts/))

將下述寫入 Dockerfile，於 build 的時候，就會讀取 /tmp/hosts 來操作囉~

### 相關網頁

- - [docker 之 dockerFile (解決 hosts，hostname 問題)](https://blog.csdn.net/libo222/article/details/52669093)
    - [docker - Modify hosts file in dockerfile](https://serverfault.com/questions/777714/modify-hosts-file-in-dockerfil)