在Linux系统上更改DNS服务器(使用systemd-resolved)

本指南将指导您如何在您的Linux系统上更改DNS服务器,使用的是systemd-resolved服务。
免责声明: 修改系统文件和服务可能会导致系统不稳定或其他问题。在进行更改前,请确保备份重要的文件和配置。

步骤说明

1. 切换到 /etc 目录

首先,切换到 /etc 目录:

cd /etc

2. 备份现有的 resolv.conf 文件(可选)

在进行任何更改之前,最好备份现有的 resolv.conf 文件:

mv /etc/resolv.conf /etc/resolv.conf.bak

3. 编辑 resolved.conf 文件

使用 vi 文本编辑器编辑 resolved.conf 文件:

vi /etc/systemd/resolved.conf

4. 修改DNS设置

resolved.conf 文件中,添加或修改 DNS= 行以指定您想要使用的DNS服务器。例如:

[Resolve]
DNS=8.8.8.8 114.114.114.114

保存并退出编辑器(按下 Esc 键,然后输入 :wq 并按 Enter 键)。

5. 重启 systemd-resolved 服务

重启 systemd-resolved 服务来应用新的DNS设置:

sudo systemctl restart systemd-resolved

6. 启用 systemd-resolved 服务

确保 systemd-resolved 服务在启动时自动运行:

sudo systemctl enable systemd-resolved

7. 创建 resolv.conf 的符号链接

创建一个从 /run/systemd/resolve/resolv.conf/etc/resolv.conf 的符号链接。这确保了 systemd-resolved 生成的 resolv.conf 文件被使用:

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

8. 重启系统(可选)

重启系统以确保所有更改生效。这一步是可选的,因为重启 systemd-resolved 服务通常就足够了:

sudo reboot

9.修改成功后查看配置

cat /etc/resolv.conf

额外注意事项

  • 原始命令中的 rm resolv.conf 已被删除,因为它不是必要的,并且可能会导致问题。
  • 推荐在完成这些更改后测试网络连接,以确保一切正常。
作者:lzx  创建时间:2025-02-14 11:29
最后编辑:lzx  更新时间:2025-04-16 11:40