域名系统(英文:Domain Name System,缩写:DNS)是互联网的一项服务。它作为将域名和IP地址相互映射的一个分布式数据库,能够使人更方便地访问互联网。DNS使用TCP和UDP端口53。当前,对于每一级域名长度的限制是63个字符,域名总长度则不能超过253个字符。
俗话说得好,网络优化,必先优化DNS。下面介绍两种最简单、最实在的DNS优化方法:
- 超时
在工作中我们经常遇到错误提示(DNS lookup timed out / Connection timed out
),这就是DNS超时。要解决超时,最简单的就是通过/etc/resolv.conf
来控制超时。
- 重试
因为某个DNS服务超时了,底层就会根据你的设置自动重试。但是如果重试次数过多就会影响用户体验。所以我们也能通过/etc/resolv.conf
来控制重试。
不管是超时、还是重试,我们都提到了使用/etc/resolv.conf
, 那什么是/etc/resolv.conf
呢?答案是resolver configuration file
。
The resolver is a set of routines in the C library that provide access to the Internet Domain Name System (DNS). The resolver configuration file contains information that is read by the resolver routines the first time they are invoked by a process. The file is designed to be human readable and contains a list of keywords with values that provide various types of resolver information.
If this file does not exist, only the name server on the local machine will be queried; the domain name is determined from the hostname and the domain search path is constructed from the domain name.
一个最简单的/etc/resolv.conf
文件如下:
# Generated by NetworkManager
nameserver 10.xx.x.xx
nameserver 10.xx.x.xx
nameserver 10.xx.x.xx
一个带有超时与重试的/etc/resolv.conf
文件如下:
options timeout:2 attempts:3
nameserver 10.xx.x.xx
nameserver 10.xx.x.xx
nameserver 10.xx.x.xx
顾名思义,timeout(超时)/attempts(重试),超时默认是5秒,重试默认是2次。我们可以修改为超时2秒,重试3次。
当然,/etc/resolv.conf
文件还有很多其他重要配置,如rotate可以实现负载均衡、no-check-names禁止无效字符检查。
国内常用的DNS服务
114.114.114.114 # 电信DNS服务
114.114.115.115 # 电信DNS服务
119.29.29.29 # 腾讯DNS服务
182.254.116.116 # 腾讯DNS服务
223.5.5.5 # 阿里DNS服务
223.6.6.6 # 阿里DNS服务
180.76.76.76 # 百度DNS服务
相关调试命令:dig、nslookup、strace
dig www.baidu.com
; <<>> DiG 9.10.6 <<>> www.baidu.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55250
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;www.baidu.com. IN A
;; ANSWER SECTION:
www.baidu.com. 42 IN CNAME www.a.shifen.com.
www.a.shifen.com. 42 IN A 180.xxx.xx.x
www.a.shifen.com. 42 IN A 180.xxx.xx.x
;; Query time: 65 msec
;; SERVER: 223.x.x.x#53(223.x.x.x)
;; WHEN: Wed Aug 19 19:05:04 CST 2020
;; MSG SIZE rcvd: 90
参考文档:man resolv(5)
– end –