oLeiShen 2020-06-25
今天有写过一个简单的基于nginx 的stream 代理dns server的服务,以下是集成coredns 的一个demo
同时也包含了consul 以及使用coredns 的rewrite 以及loadbalance 插件
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" consul: image: consul networks: service1_net: ipv4_address: 192.168.1.3 ports: - "8500:8500" 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
worker_processes 1; user root; events { worker_connections 1024; } # nginx dns server proxy 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; # 基于nginx 代理的nginx 请求内容 location / { index index.html; default_type text/html; set $kuaidi100 "www.kuaidi100.com"; 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; } } }
dalongrong.com:53 { log health rewrite stop { name regex (.*)-(dc1)\.dalongrong\.com {1}.service.{2}.consul answer name (.*)\.service\.(dc1)\.consul {1}-{2}.dalongrong.com } forward . 192.168.1.3:8600 } ? .:53 { log health cache 30 loadbalance round_robin forward . 8.8.8.8 8.8.4.4 114.114.114.114 }
注意需要先创建dns.log 文件
docker-compose u -d
curl -X PUT -d ‘{"ID": "openresty","Name": "openresty","Address": "192.168.1.2","Port": 80}‘ http://127.0.0.1:8500/v1/agent/service/register
dig @127.0.0.1 openresty-dc1.dalongrong.com
效果
以上只是一个简单的学习使用,实际上我们如果我们集成了openresty,同时结合consul 的cname特性,可以方便的基于consul 的dns
功能进行动态反向代理,同时基于coredns 强大的plugin 能力,构建灵活的软件架构
https://github.com/rongfengliang/nginx-coredns-consul-learning
https://coredns.io/plugins/
https://www.consul.io/api-docs/agent/service