在開發、測試和正式環境中,咱們總但願經過同一個域名找到對應環境中的服務實例,簡化配置流程,例如在測試環境中,讓api.changjinglu.net關聯到IP爲192.168.1.34的測試服務器,而在正式環境中,讓api.changjinglu.net關聯到阿里雲的正式服務器IP。shell
咱們如今的解決方案是在本機的/etc/hosts文件中記錄相應的域名IP映射關係,本機在嘗試解析一個域名時,會先去/etc/hosts中查找該域名對應的IP,並訪問相應IP的服務器。只有當/etc/hosts中沒有該域名的記錄時,本機纔會去DNS服務器進行域名解析。本機解析域名的優先級爲DNS緩存 > /etc/hosts > DNS服務。ubuntu
這個解決方案稍顯繁瑣,由於每臺機器都必須在本身的/etc/hosts文件中配置正確的域名IP映射關係,一旦映射關係發生改變,全部機器又必須所有作相應的修改。一個更簡潔的解決方案是構建一個本地DNS服務器,讓路由器指向該本地DNS服務器,讓它統一管理全部通用的域名IP映射,若是個別開發者有本身的特別須要,能夠利用域名解析的優先級順序,經過修改本身本機的/etc/hosts覆蓋本地DNS服務的映射關係。使用這個新方案,當局域網中新增某個服務或某個原有服務改變IP地址時,只須要在本地DNS服務器上新增或修改映射配置,局域網中的全部機器無需作修改,就能享受到正確的映射關係了。api
下面講一講如何經過Dnsmasq實現這個新方案。緩存
我將本地DNS服務安裝在了192.168.1.98上,由於該測試服務器的系統是ubuntu,使用自帶的包管理器下載並安裝Dnsmasq最簡潔。服務器
sudo apt-get install dnsmasq
Dnsmasq全部的配置都在/etc/dnsmasq.conf文件中完成,按照須要簡單作了如下修改。ide
#首先配置resolv-file,這個參數表示dnsmasq會從這個指定的文件中尋找上游DNS服務器 resolv-file=/etc/resolv.dnsmasq.conf #單設置127.0.0.1爲只能本機使用,單設置本機IP爲只能內部全網使用而本機不能用,這裏須要同時設置二者 listen-address=127.0.0.1,192.168.1.98 #dnsmasq緩存設置 cache-size=1024
而後根據本身設置的resolv-file=/etc/resolv.dnsmasq.conf,配置/etc/resolv.dnsmasq.conf文件,指定上游DNS服務器測試
nameserver 114.114.114.114
按以上配置配置好Dnsmasq並啓動後,會發現Dnsmasq沒法正常解析域名,使用ps -ef | grep dnsmasq查看後發現以下信息this
dnsmasq 10384 1 0 15:16 ? 00:00:00 /usr/sbin/dnsmasq -x /var/run/dnsmasq/dnsmasq.pid -u dnsmasq -r /var/run/dnsmasq/resolv.conf -7 /etc/ dnsmasq.d,.dpkg-dist,.dpkg-old,.dpkg-new --local-service --trust-anchor=.,19036,8,2,49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5
其中dnsmasq -r /var/run/dnsmasq/resolv.conf說明Dnsmasq是從/var/run/dnsmasq/resolv.conf文件中獲取上游DNS服務器,而非咱們指定的resolv-file=/etc/resolv.dnsmasq.conf。
查閱了無數文檔之後,發如今/etc/default/dnsmasq中有一個IGNORE_RESOLVCONF屬性,說明以下阿里雲
# If the resolvconf package is installed, dnsmasq will use its output # rather than the contents of /etc/resolv.conf to find upstream # nameservers. Uncommenting this line inhibits this behaviour. # Note that including a "resolv-file=<filename>" line in # /etc/dnsmasq.conf is not enough to override resolvconf if it is # installed: the line below must be uncommented. # IGNORE_RESOLVCONF=yes
這裏必須取消IGNORE_RESOLVCONF=yes前的註釋,才能讓resolv-file=/etc/resolv.dnsmasq.conf生效。spa
大功告成,啓動Dnsmasq。
sudo service dnsmasq start