自建dns服务器
大部分公司在项目比较多的情况下 可能会在公司内部搭建自己的dns服务器 但是使用bind程序过于繁杂 于是使用coredns+etcd集成了一个自己的dns服务器 并编写了一个简陋的管理页面 并实现docker-compos 一键部署 鉴定方便
github: https://github.com/younglinuxer/coredns-web.git
执行下面命令即可部署完成整个dns服务
git clone https://github.com/younglinuxer/coredns-web.git && cd coredns-web && docker-compose up
#将电脑的dns指向服务器即可 或者在网络设备上指定下放dns服务器地址即可
coredns 配置文件说明
.:53 {
etcd {
# 启用存根区域功能。 stubzone仅在位于指定的第一个区域下方的etcd树中完成
stubzones
# etcd里面的路径。默认为/coredns,以后所有的dns记录就是存储在该存根路径底下
path /coredns
# etcd访问地址,多个空格分开
endpoint http://etcd-dns:2379
# upstream设置要使用的上游解析程序解决指向外部域名的在etcd(认为CNAME)中找到的外部域名。
upstream 114.114.114.114:53 8.8.8.8:53 8.8.4.4:53 /etc/resolv.conf
# 如果区域匹配但不能生成记录,则将请求传递给下一个插件
fallthrough
}
health
prometheus
cache 160
reload 6s
# 负载均衡,开启DNS记录轮询策略
loadbalance
# 上面etcd未查询到的请求转发给设置的DNS服务器解析
forward . 8.8.8.8:53 8.8.4.4:53 /etc/resolv.conf
# 打印日志
log
# 输出错误
errors
}
python 调用etcd示例
#!/usr/bin/env python
# encoding: utf-8
from flask import Flask, render_template, request, flash,redirect,url_for
import etcd3
import json,re
# 配置etcd的链接地址 etcd-dns为docker-compose中的etcd的服务名
etcd = etcd3.client(host='etcd-dns', port='2379')
def get_dns():
# 获取etcd中的所有值
data = etcd.get_all_response()
k_dict = []
for i in data.kvs:
# 取出包含 /coredns/的数据条目 该条目下为dns解析记录
if (str(i.key).split('/')[0]) == '' and (str(i.key).split('/')[1] == 'coredns'):
domain = i.key.split('/')
domain.reverse()
del domain[-2:]
result = {'domain': '.'.join(str(i) for i in domain), 'ip': json.loads(i.value)['host']}
k_dict.append(result)
return k_dict
def add_dns(domain='www.example.com', host='127.0.0.1'):
key = domain.split('.')
key.append('coredns')
key.reverse()
value = '{"host":"%s","ttl":10}' % host
d_key = '/' + "/".join(str(i) for i in key)
print d_key, value
# 拼装域名后将值写入etcd
# 写入格式 etcdctl put /coredns/com/aaa/www '{"host":"0.0.0.0","ttl":10}'
etcd.put(d_key, value)
docker-compose说明
version: '3'
services:
# etcd service
etcd-dns:
image: quay.io/coreos/etcd:v3.4.14
container_name: etcd-dns
restart: always
environment:
- ETCDCTL_API=3
- TZ=CST-8
- LANG=zh_CN.UTF-8
command:
- "/usr/local/bin/etcd"
- "--name=etcd-dns"
- "--data-dir=/etcd-data"
- "--advertise-client-urls=http://0.0.0.0:2379"
- "--listen-client-urls=http://0.0.0.0:2379"
- "--debug=true"
volumes:
- ./etcd/data:/etcd-data:rw
ports:
- 2379:2379
- 2380:2380
# coredns service
coredns:
image: coredns/coredns:1.8.0
container_name: coredns
restart: always
#network_mode: host
depends_on:
- etcd-dns
command: -conf /etc/coredns/Corefile
volumes:
- ./coredns/conf:/etc/coredns:ro
ports:
- 53:53/tcp
- 53:53/udp
web:
image: younglinuxer/coredns-web:v1
container_name: coredns-web
restart: always
depends_on:
- etcd-dns
ports:
- 8081:8081
使用及 验证
界面使用
更改qq.com域名解析