rocky-consul
rocky middleware to easily setup a reverse HTTP proxy with service discovery and load balancer using Consul.
Essentially, this middleware will ask to Consul on every interval (configurable) to retrieve a list of URLs of a specific service (e.g: API, CDN, storage), and then them will be provided to rocky
in order to balance the incoming HTTP traffic between those URLs.
Name | consul |
Rocky | +0.2 |
Scope | global, route |
Type | forward / balance |
Installation
npm install rocky-consul --save
Usage
var rocky = var consul = var proxy =
Plug in as global middleware
proxy // Handle all the trafficproxyall'/*' proxyconsole
Plug in as route level middleware
proxy // Handle the rest of the traffic without using Consulproxyall'/*' proxyconsole
API
=>
Function(req, res, next)
consul(options) Return a middleware function
with the Consul client as static property function.consul
.
Options
- service
string
- Consul service. Required - servers
array<string>
- List of Consul servers URLs. Required - datacenter
string
- Custom datacenter to use. If not defined the default one will be used - tag
string
- Use a specific tag for the service - defaultServers
array<string>
- Optional list of default target servers to balance. This avoid asking Consul the first time. - protocol
string
- Transport URI protocol. Default tohttp
- timeout
number
- Consul server timeout in miliseconds. Default to5000
= 5 seconds - interval
number
- Consul servers update interval in miliseconds. Default to120000
= 2 minutes - headers
object
- Map of key-value headers to send to Consul - auth
string
- Basic authentication for Consul. E.g:user:p@s$
- onRequest
function
- Executes this function before sending a request to Consul server. Passed arguments are:httpOpts
- onUpdate
function
- Executes this function on every servers update. Passed arguments are:err, servers
- onResponse
function
- Executes this function on every Consul server response. Passed arguments are:err, servers, res
Consul(options)
Internally used micro Consul client interface.
consul#servers(cb)
Returns the Consul servers for the given service.
Passed arguments to the callback are: cb(err, servers)
.
consul#update(cb)
Perform the servers update asking to Consul
Passed arguments to the callback are: cb(err, servers)
.
consul#startInterval()
Start the servers update interval as recurrent job for the given miliseconds defined at options.interval
.
You should not call this method unless you already called stopInterval()
.
consul#stopInterval()
Stop server update interval process.
License
MIT - Tomas Aparicio