Ubuntu-18.04配置静态IP和DNS

Ubuntu-18.04配置静态IP和之前版本有所不同,需要通过netplan工具配置

推荐-通过netplan工具同时更改IP和DNS

Ubuntu-18.04配置静态IP需要更改netplan的yaml文件,而非之前的/etc/network/interfaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$ sudo vim /etc/netplan/00-installer-config.yaml
network:
ethernets:
ens160:
dhcp4: no
addresses:
- 192.168.80.10/24
gateway4: 192.168.80.2
nameservers:
addresses:
- 192.168.80.2
- 223.5.5.5
search: []
optional: true
version: 2
$ sudo netplan apply
$ networkctl status
● State: routable
Address: 192.168.80.10 on ens160
fe80::20c:29ff:fe18:95a3 on ens160
Gateway: 192.168.80.2 on ens160
DNS: 192.168.80.2
223.5.5.5
# 更改软链接到正确的resolv.conf文件(原因如下说明)
$ sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

通过systemd-resolved服务更改DNS,此为全局DNS,优先于netplan配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 默认系统DNS查询走的是本地127,即通过systemd-resolved服务
$ dig baidu.com
...
;; Query time: 6 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
...
$ more /etc/resolv.conf
nameserver 127.0.0.53
options edns0
$ sudo ss -tunlp
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=2200,fd=12))
tcp LISTEN 0 128 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=2200,fd=13))
tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=1158,fd=3))
# 更改系统DNS配置并重启systemd-resolved服务
$ sudo vim /etc/systemd/resolved.conf
[Resolve]
DNS=192.168.80.2 223.5.5.5
LLMNR=no
$ sudo systemctl restart systemd-resolved.service
$ systemd-resolve --status
Global
DNS Servers: 192.168.80.2
223.5.5.5
DNSSEC NTA: 10.in-addr.arpa
...
# 但是查看resolv.conf文件还是127?发现这个文件是个软链接,而且链接的原文件配置有问题
$ more /etc/resolv.conf
nameserver 127.0.0.53
options edns0
$ ll /etc/resolv.conf
lrwxrwxrwx 1 root root 39 Aug 6 22:35 /etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf
$ ll /run/systemd/resolve/
-rw-r--r-- 1 systemd-resolve systemd-resolve 610 Dec 14 15:05 resolv.conf
-rw-r--r-- 1 systemd-resolve systemd-resolve 715 Dec 14 15:05 stub-resolv.conf
$ more /run/systemd/resolve/resolv.conf
nameserver 192.168.80.2
nameserver 223.5.5.5
$ more /run/systemd/resolve/stub-resolv.conf
nameserver 127.0.0.53
options edns0
# 更改软链接到正确的resolv.conf文件
$ sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf
$ more /etc/resolv.conf
nameserver 192.168.80.2
nameserver 223.5.5.5
# 再次测试DNS查询结果返回的SERVER地址就正常了
$ dig baidu.com
...
;; Query time: 0 msec
;; SERVER: 192.168.80.2#53(192.168.80.2)