最近一台 Ubuntu 出现了网络问题,ping baidu.com 出现了 temporary failure in name resolution 报错,根据我的经验这是服务器的 DNS 出现了问题,特此在本文记录一下如何设置 DNS 的过程.

修改 netplan 配置文件

我先尝试修改 netplan 的配置文件,编辑相应的配置文件,我这里的路径是 /etc/netplan/00-installer-config.yaml, 修改后的内容如下:

network:
  ethernets:
    ens160:
      addresses:
      - 192.168.1.51/24
      gateway4: 192.168.1.1
      nameservers:
        addresses:
        - 114.114.114.114
        search: []
  version: 2

修改后执行 netplan apply, 重新 ping 后发现没有效果,未能解决问题。

修改 /etc/resolv.conf

我们还可以通过修改 /etc/resolv.conf 文件来设置 dns, 虽然通过修改此文件可以解决我们的问题,但编辑 /etc/resolv.conf 文件时,发现了一行注释 This file is managed by man:systemd-resolved(8). Do not edit. 可以得知这个文件是由man:systemd-resolved(8) 管理,/etc/resolv.conf 是一个动态生成的文件, 下次重启服务器时此文件还会恢复到默认的内容,所以此方案只适合临时解决,不能一次性解决问题。

接下来我来介绍如何永久的修改 /etc/resolv.conf

修改 /etc/systemd/resolved.conf 文件

#  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=114.114.114.114 8.8.8.8
#FallbackDNS=
#Domains=
#LLMNR=no
#MulticastDNS=no
#DNSSEC=no
#DNSOverTLS=no
#Cache=no-negative
#DNSStubListener=yes
#ReadEtcHosts=yes
~                                                                                                                                       ~                                                                                                                                       ~                                                                                                                                       ~                                                                                                                                       ~                                                                                                                                       ~                                                                                                                                       ~                                      

添加要修改的 dns 信息。

重启服务

接下来执行如下命令:

sudo systemctl restart systemd-resolved
sudo systemctl enable systemd-resolved
 
sudo mv /etc/resolv.conf  /etc/resolv.conf.bak
sudo ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf

再查看/etc/resolv.conf文件就可以看到新的dns信息已经写入其中了,接下来再使用就不会被重置。