使用coredns 的template plugin实现一个xip 服务
xip dns 服务在我们的实际开发中,还是挺有用的,我们可以基于dns模式方便的进行软件开发,同时结合nginx 的虚拟主机,可以实现灵活的软件部署,以下是基于coredns 的template plugin 实现一个简单,但是高效的xip 服务
xip 格式说明
- 参考格式
resolves to 10.0.0.1
resolves to 10.0.0.2
resolves to 10.0.0.3
resolves to 10.0.0.4
- 说明
我们主要实现以下格式的
resolves to 10.0.0.3
环境准备
- docker-compose 文件
version: "3"
services:
lb:
image: openresty/openresty:alpine
networks:
service1_net:
ipv4_address: 192.168.1.2
volumes:
- "./nginx-lb.conf:/usr/local/openresty/nginx/conf/nginx.conf"
- "./dns.log:/var/log/nginx/dns.log"
ports:
- "53:53/udp"
- "80:80"
- "53:53/tcp"
coredns:
image: coredns/coredns:1.7.0
networks:
service1_net:
ipv4_address: 192.168.1.4
volumes:
- "./Corefile:/opt/Corefile"
command: -conf /opt/Corefile
networks:
service1_net:
ipam:
driver: default
config:
- subnet: 192.168.1.0/16
- 说明
基于nginx做dns 的proxy,基于coredns提供xip服务 - nginx 配置
worker_processes 1;
user root;
events {
worker_connections 1024;
}
stream {
upstream dns_servers {
server 192.168.1.4:53;
}
server {
listen 53 udp;
listen 53; #tcp
proxy_pass dns_servers;
error_log /var/log/nginx/dns.log info;
}
}
http {
include mime.types;
default_type text/html;
gzip on;
resolver 127.0.0.1 ipv6=off valid=30s;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
server {
listen 80;
charset utf-8;
default_type text/html;
location / {
index index.html;
default_type text/html;
set $kuaidi100 "";
proxy_pass https://$kuaidi100;
proxy_redirect off;
proxy_set_header Bloom-Request-Shard 1;
proxy_read_timeout 10000;
proxy_send_timeout 10000;
proxy_buffer_size 1M;
proxy_buffers 8 1M;
proxy_busy_buffers_size 1M;
proxy_temp_file_write_size 1M;
proxy_set_header Host $kuaidi100;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
- coredns 配置
Corefile 文件
我们基于正则以及template plugin生成xip服务,实际上很简单,我们利用了coredns 提供的变量
以及正则分组别名,快速的实现了一个xip服务
:53 {
log
template IN A {
match ^(?P<a>\w+)\.(?P<b>\d+\.\d+\.\d+\.\d+)\.dalongrong\.com\.$
answer "{{ .Name }} 60 IN A {{ .Group.b }}"
authority ". 60 IN NS ns0.."
authority ". 60 IN NS ns1.."
additional "ns0.. 60 IN A 203.0.113.8"
additional "ns1.. 60 IN A 198.51.100.8"
fallthrough
}
}
.:53 {
log
health
cache 30
loadbalance round_robin
forward . 8.8.8.8 8.8.4.4 114.114.114.114
}
- 启动
docker-compose up -d
测试
- dig 命令
我们希望.. 解析的dns为 就可以实现此功能了
命令
dig @127.0.0.1 openresty.192.168.0.190.
效果
说明
以上支持实现了部分xip服务,但是已经够我们实际使用了,具体其他模式的主要是正则的编写,有空了可以写下
参考支持xip 的一个coredns 配置
:53 {
log
template IN A {
match (\D*?)\.?(?P<b>\d+\.\d+\.\d+\.\d+)\.dalongrong\.com\.$
answer "{{ .Name }} 60 IN A {{ .Group.b }}"
authority ". 60 IN NS ns0.."
authority ". 60 IN NS ns1.."
additional "ns0.. 60 IN A 203.0.113.8"
additional "ns1.. 60 IN A 198.51.100.8"
fallthrough
}
}
.:53 {
log
health
cache 30
loadbalance round_robin
forward . 8.8.8.8 8.8.4.4 114.114.114.114
}