1、問題描述
ping不通域名,比如“ping www.baidu.com”時,報錯“ping: unknown host www.baidu.com”。這是因爲ubuntu默認情況下沒有設置DNS。
在ubuntu上設置DNS的方法,修改“/etc/resolv.conf”,添加“nameserver 8.8.8.8”,但是重啓後就失效了。
2、原因查找
在“/etc/resolv.conf”中開頭有如下內容:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
這裏已經明確說明,resolv.conf是由resolvconf命令動態生成的,不要編輯這個文件。
resolvconf是什麼?
resolvconf 是"域名服務信息"管理工具,說白了就是管理ubuntu系統的DSN,包括添加、刪除、更新、使能或禁止更新等。
使用方法:resolvconf (-d IFACE|-a IFACE|-u|–enable-updates|–disable-updates|–updates-are-enabled)
可以使用man查看詳細信息:man resolvconf
如何生成的resolv.conf?
ubunut啓動後調用初始化腳本:/etc/init.d/resolvconf start
83 start)
84 # The "start" method should only be used at boot time.
85 # Don't run this on package upgrade, for example.
86 log_action_begin_msg "Setting up resolvconf"
87 # Wipe runtime directories in case they aren't on a tmpfs
88 wipe_runtime_directories
89 # Create runtime directories in case they are on a tmpfs
90 create_runtime_directories
91 # Request a postponed update (needed in case the base file has content).
92 :> "$POSTPONED_UPDATE_FLAGFILE" || log_action_end_msg_and_exit 1 "failed requesting update"
93 # Enable updates and perform the postponed update.
94 resolvconf --enable-updates || log_action_end_msg_and_exit 1 "failed to enable updates"
95 log_action_end_msg_and_exit 0
96 ;;
對上面這段腳本的解釋:
首先,註釋裏面提示==/etc/init.d/resolvconf start==只能在系統啓動時調用一次,因爲它會在/run/中創建resolvconf及相關文件目錄。
wipe_runtime_directories:清除/run/resolvconf目錄
create_runtime_directories:創建/run/resolvconf/interface目錄
:> “$POSTPONED_UPDATE_FLAGFILE” 創建文件 /run/resolvconf/postponed-update,這個文件下面會用到。
resolvconf --enable-updates:resolvconf路徑是/sbin/resolvconf
/sbin/resolvconf也是一個腳本,執行 --enable-updates 選項
--enable-updates)
: >| "$ENABLE_UPDATES_FLAGFILE" || exit 1
if [ -e "$POSTPONED_UPDATE_FLAGFILE" ] ; then
(update_and_exit -u) || :
fi
exit 0
對上面這段腳本的解釋:
創建文件 /run/resolvconf/enable-updates;
如果文件 /run/resolvconf/postponed-update存在,則執行(update_and_exit -u),這個文件在上面的步驟中已經創建;
update_and_exit函數如下
56 update_and_exit()
57 {
58 rm -f "$POSTPONED_UPDATE_FLAGFILE"
59 exec run-parts ${1:+--arg="$1"} ${2:+--arg="$2"} /etc/resolvconf/update.d
60 }
刪除:/run/resolvconf/postponed-update
run-parts功能:批量執行目錄下的腳本;
/etc/resolvconf/update.d下只有一個腳本libc;
libc功能是用 /etc/resolvconf/resolv.conf.d 目錄下的三個文件head、base、tail生成/run/resolvconf/resolv.conf,並創建軟鏈接/etc/resolv.conf
3、解決方法
要想設置永久的DNS,一個正經的辦法是修改 /etc/resolvconf/resolv.conf.d/base
nameserver 8.8.8.8
nameserver 8.8.4.4
修改完後執行:
/sbin/resolvconf -u
再重啓後就不用再設置DNS了