记一次自建 DoH 服务器

记一次自建 DoH 服务器

Neurocoda

CoreDNS

CoreDNS 是一个灵活且功能强大的 DNS 服务器,支持多种插件扩展。它非常适合用于搭建 DoH 服务。

初始化

安装必要组件

首先,更新系统并安装所需的软件包,包括 Docker Compose 和 Certbot(用于获取 SSL 证书)。

1
sudo apt update && sudo apt upgrade -y && sudo apt install -y docker-compose certbot

配置防火墙

确保服务器的安全性,配置防火墙规则,允许必要的端口(22、80 和 443)。

1
2
3
4
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

获取 SSL 证书

使用 Certbot 获取 SSL 证书。请将 <DOMAIN> 替换为你的实际域名。

1
sudo certbot certonly --standalone -d <DOMAIN>

注意:确保域名已正确解析到你的服务器 IP,并且 80 端口未被其他服务占用。

配置并部署 CoreDNS

我们将通过 Docker 来运行 CoreDNS。

创建 CoreDNS 配置目录

创建配置文件存放目录。

1
sudo mkdir -p /etc/coredns

编写 CoreDNS 配置文件

创建并编辑 /etc/coredns/Corefile

1
sudo vim /etc/coredns/Corefile

在文件中添加以下内容,记得将 <DOMAIN> 替换为你的实际域名:

1
2
3
4
5
6
7
8
https://.:443 {
tls /etc/letsencrypt/live/<DOMAIN>/fullchain.pem /etc/letsencrypt/live/<DOMAIN>/privkey.pem
bind 0.0.0.0:443
forward . 1.1.1.1 8.8.8.8
log
errors
cache 300
}

配置说明:

  • <DOMAIN>:443:在 443 端口上监听来自指定域名的 HTTPS 请求。
  • tls:指定 SSL 证书和私钥的路径。
  • bind 0.0.0.0:443:绑定所有网络接口的 443 端口,允许外部访问。
  • forward . 1.1.1.1 8.8.8.8:将 DNS 请求转发到 Cloudflare (1.1.1.1) 和 Google (8.8.8.8) 的公共 DNS 服务器。
  • logerrors:启用日志记录和错误记录,便于调试。
  • cache 300:启用 DNS 缓存,缓存时间为 300 秒,提高查询速度。

运行 CoreDNS 容器

使用 Docker 运行 CoreDNS 容器。确保将 <DOMAIN> 替换为你的实际域名。

1
2
3
4
5
6
7
8
9
sudo docker run -d \\
--name coredns \\
--restart unless-stopped \\
--network host \\
-v /etc/coredns:/etc/coredns \\
-v /etc/letsencrypt/live/<DOMAIN>/fullchain.pem:/etc/letsencrypt/live/<DOMAIN>/fullchain.pem \\
-v /etc/letsencrypt/live/<DOMAIN>/privkey.pem:/etc/letsencrypt/live/<DOMAIN>/privkey.pem \\
coredns/coredns \\
-conf /etc/coredns/Corefile

运行说明:

  • -network host:使用主机的网络堆栈,允许 CoreDNS 在主机的 443 端口上监听。
  • v /etc/coredns:/etc/coredns:将主机的配置目录挂载到容器内,方便管理配置文件。
  • v /etc/letsencrypt/live/<DOMAIN>/fullchain.pemv /etc/letsencrypt/live/<DOMAIN>/privkey.pem:将 SSL 证书和私钥挂载到容器内,确保 CoreDNS 能够使用 HTTPS。

验证 CoreDNS 运行状态

确保 CoreDNS 容器正在运行,并监听正确的端口。

1
sudo docker ps | grep coredns

你应该能看到类似如下的输出,表示 CoreDNS 容器正在运行并监听 443 端口:

1
2
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                                       NAMES
<container_id> coredns/coredns "/coredns -conf /etc…" X seconds ago Up X seconds 0.0.0.0:443->443/tcp coredns

配置客户端使用 DoH

完成上述步骤后,你的 DoH 服务器已经搭建完成。接下来,需要在客户端设备上配置 DNS 设置,使用 https://<DOMAIN>/dns-query 作为 DoH 服务器地址。

自动更新 SSL 证书

Certbot 获取的 SSL 证书有效期为 90 天,建议设置定时任务自动更新证书,并重启 CoreDNS 容器。

创建一个定时任务,每天检查并更新证书:

1
sudo crontab -e

添加以下内容:

1
0 2 1 * * certbot renew --quiet && sudo docker restart coredns

此任务将在每个月1号的凌晨 2 点运行,自动更新证书并重启 CoreDNS 容器。

参考资料

CoreDNS Manual
Certbot
Home
DNS over HTTPS

  • Title: 记一次自建 DoH 服务器
  • Author: Neurocoda
  • Created at : 2024-09-21 11:41:49
  • Updated at : 2024-09-21 11:41:49
  • Link: https://neurocoda.com/p/cf8cf045.html
  • License: This work is licensed under CC BY-ND 4.0.
Comments