阿里云ECS上搭建coredns实现内网域名解析

前言

已经在一台阿里云ecs上搭建好openvpn, 弹性公网IP绑定这台ECS,剩下所有ecs都在华北二区,一个vpc内,没有公网IP。通过购买阿里云 云解析DNS 服务,使用PrivateZone,搭建云上内网DNS服务。本地PC挂上vpn后,连接vpn成功,ping vpc内的 ecs服务器能ping通,ping 内网域名不通,咨询阿里云技术,没有解决,推销让购买他们自己的vpn。最终删掉 阿里云 云解析DNS 服务,自己在 openvpn 那台ecs上搭建coredns,实现本地PC挂上vpn后,能ping通 阿里云ecs 内网域名。

搭建coredns

[root@openvpn ~]# wget https://github.com/coredns/coredns/releases/download/v1.8.7/coredns_1.8.7_linux_amd64.tgz
[root@openvpn ~]# tar zxf coredns_1.8.7_linux_amd64.tgz
You have new mail in /var/spool/mail/root
[root@openvpn ~]# ll
total 60968
-rwxr-xr-x 1   33 tape 48738304 Jan 14 22:11 coredns
-rw-r--r-- 1 root root 13675360 Feb  8 15:40 coredns_1.8.7_linux_amd64.tgz
-rw-r--r-- 1 root root     1724 Jan 26 17:09 openvpn.sh
-rw-r--r-- 1 root root      919 Feb  4 22:59 send-mail.py
-rw-r--r-- 1 root root      111 Jan 26 13:22 test.sh
-rw-r--r-- 1 root root     1289 Feb  7 09:42 useraddvpn.sh
[root@openvpn ~]# mv coredns /usr/bin/
[root@openvpn ~]# useradd coredns -s /sbin/nologin
[root@openvpn ~]# mkdir /etc/coredns
[root@openvpn ~]# cat /etc/coredns/Corefile
[root@openvpn coredns]# cat /etc/coredns/Corefile
.:53 {
  # 绑定内网dns的 ip
  bind 172.16.0.40 
  # 先走本机的hosts
  # https://coredns.io/plugins/hosts/
  hosts {
    # 需要解析的域名少我们这里直接用hosts插件即可完成需求
    172.16.0.39    harbor.xxx.com  #每台ECS自定义的内网域名和对应的内网ip,按行添加即可
    172.16.0.42    dev.xxx.com
    172.16.0.56    build-agent.xxx.com
    
    # ttl
    ttl 60
    # 重载hosts配置
    reload 1m
    # 继续执行
    fallthrough
  }
  # file enables serving zone data from an RFC 1035-style master file.
  # https://coredns.io/plugins/file/
  # file service.signed service
  # 最后所有的都转发到系统配置的上游dns服务器去解析
  forward . /etc/resolv.conf
  # 缓存时间ttl,
  cache 10
  # 自动加载配置文件的间隔时间,建议降低时间,生效快
  reload 2s
  # 输出日志
  log 
  # 输出错误
  errors
}


[root@openvpn coredns]# 

[root@openvpn ~]# cat /usr/lib/systemd/system/coredns.service
[Unit]
Description=CoreDNS DNS server
Documentation=https://coredns.io
After=network.target

[Service]
PermissionsStartOnly=true
LimitNOFILE=1048576
LimitNPROC=512
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
User=coredns
ExecStart=/usr/bin/coredns -conf=/etc/coredns/Corefile
ExecReload=/bin/kill -SIGUSR1 $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

[root@openvpn ~]# systemctl enable coredns
Created symlink from /etc/systemd/system/multi-user.target.wants/coredns.service to /usr/lib/systemd/system/coredns.service.
[root@openvpn ~]# systemctl restart coredns

每台ECS修改/etc/resolv.conf

剩下内网的ecs修改/etc/resolv.conf,添加 dns服务器的ip地址

[root@harbor ~]# cat /etc/resolv.conf 
#options timeout:2 attempts:3 rotate single-request-reopen
#; generated by /usr/sbin/dhclient-script
#nameserver 100.100.2.136
#nameserver 100.100.2.138
nameserver 172.16.0.40
[root@harbor ~]# 

 

本地测试域名解析

本地PC挂上vpn后,测试,ping 阿里云 vpc内地 私网域名,正常。

 

posted @ 2022-02-08 18:14  menglingqian  阅读(1119)  评论(0编辑  收藏  举报