Skip to content

Instantly share code, notes, and snippets.

@iwinux
Created May 27, 2019 10:45
Show Gist options
  • Save iwinux/4eb13fd526d71fe2c4d1a28171b8ab3e to your computer and use it in GitHub Desktop.
Save iwinux/4eb13fd526d71fe2c4d1a28171b8ab3e to your computer and use it in GitHub Desktop.
Docker 服务发现机制的简单实现
upstream default {
server 127.0.0.1:12345;
balancer_by_lua_block {
local balancer = require "ngx.balancer"
local ok, err = balancer.set_current_peer(
ngx.ctx.upstream_host or '127.0.0.1',
ngx.ctx.upstream_port or 12345
)
if not ok then
ngx.log(ngx.ERR, "failed to set upstream peer: ", err)
return ngx.exit(ngx.ERR)
end
}
}
server {
listen 127.0.0.1:12345;
server_name _;
return 404;
}
server {
listen 0.0.0.0:443 ssl http2;
server_name ~(?P<subdomain>[^.]+).example.com;
client_max_body_size 10M;
include conf.d/00_ssl.conf;
ssl_certificate /etc/nginx/ssl/example.com/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/example.com/privkey.pem;
ssl_trusted_certificate /etc/nginx/ssl/example.com/fullchain.pem;
access_by_lua_file /etc/nginx/conf.d/resolve.lua;
location / {
include conf.d/00_proxy.conf;
proxy_pass http://default;
}
}
local resolver = require 'resty.dns.resolver'
local r, err = resolver:new {
nameservers = {'127.0.0.1'},
retrans = 5,
timeout = 2000,
}
if not r then
ngx.log(ngx.ERR, 'failed to init resolver: ', err)
return
end
local subdomain = ngx.var.subdomain or 'unknown'
local hostname = subdomain .. '.cluster.local'
local options = {
qtype = r.TYPE_SRV,
additional_section = true,
}
local answers, err, tries = r:query(hostname, options, {})
if not answers then
ngx.log(ngx.ERR, 'failed to query the DNS server: ', hostname, ' ', err)
return
end
if answers.errcode then
ngx.log(
ngx.ERR,
'failed to query the DNS server: ',
answers.errcode, ' ', answers.errstr
)
return
end
local upstream_host
local upstream_port
for _, answer in ipairs(answers) do
if not upstream_host then
if string.match(answer.name or '', '^web-') then
upstream_host = answer.address
end
end
if not upstream_port then
if string.match(answer.target or '', '^web-') then
upstream_port = answer.port
end
end
if upstream_host and upstream_port then
break
end
end
ngx.ctx.upstream_host = upstream_host or '127.0.0.1'
ngx.ctx.upstream_port = upstream_port or 12345
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment