Ubuntu20.04 的 resolv.conf 会自动还原

问题

因为一些原因修改了 /etc/resolv.conf,但是重启后发现又复原了,所以网上搜了几个方案,最后确定这种方案可用,记录一下。

部分关键

cat /etc/resolv.conf

得到的结果是:

1
2
nameserver 127.0.0.53
options edns0 trust-ad

对于一些使用到的会有 Bug,比如 kubernetes 部署 calico 的时候,就会报错了。

ll /etc/resolv.conf

得到的结果是:

1
lrwxrwxrwx 1 root root 39 1月  13 01:28 /etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf

百度可知,是 systemd-resolved 这个服务的功能。

禁用这个服务的话,会发现 /etc/resolv.conf 的源文件 /run/systemd/resolve/stub-resolv.conf 这个文件没了,导致网络不通。

而删掉无效的软链,新建文件写入后,结果发现会被 NetworkManager 重写。

1
2
# Generated by NetworkManager
nameserver 127.0.0.53

解决方案

在不做任何安装操作的情况下,直接改软链的位置就好了。

具体 ubuntu 中 systemd-resolved 是怎么工作的,咱也不管,毕竟不搞系统。只需要知道它会生成 /run/systemd/resolve/resolv.conf 和 /run/systemd/resolve/stub-resolv.conf 两个文件。

其中 /run/systemd/resolve/resolv.conf 这个文件是根据 /etc/systemd/resolv.conf 来生成的。所以进行以下的操作:

更改软链:

1
ln -sf ../run/systemd/resolve/resolv.conf /etc/resolv.conf

给 /etc/systemd/resolv.conf 文件中增加 DNS,改完后的文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#  This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See resolved.conf(5) for details

[Resolve]
DNS=8.8.8.8 8.8.4.4
#FallbackDNS=
#Domains=
#LLMNR=no
#MulticastDNS=no
#DNSSEC=no
#DNSOverTLS=no
#Cache=no-negative
#DNSStubListener=yes
#ReadEtcHosts=yes

重启一下 systemd-resolvd

1
2
systemctl daemon-reload 
systemctl restart systemd-resolved.service