title: Nodejs: http-proxy redirect to available server
body: <p>I am using the <strong><a href="https://github.com/nodejitsu/node-http-proxy" rel="nofollow noreferrer">http-proxy</a></strong> npm module for connecting multiple servers to a single port.</p>
  
  <p>I wrote the following code and it's working fine:</p>
  
  <pre><code>var http = require('http');
  var httpProxy = require('http-proxy');
  
  // Proxy Address
  var proxyAddresses = [
      {
          host: "localhost",
          port: 3001
      },
      {
          host: "localhost",
          port: 3002
      }
  ];
  
  /**
   * Get port from environment and store in Express.
   */
  
  var port = normalizePort(process.env.PORT || '9090');
  app.set('port', port);
  
  //Create a set of proxy servers
  var proxyServers = proxyAddresses.map(function (target) {
      return new httpProxy.createProxyServer({
          target: target
      });
  });
  
  /**
   * Create HTTP server.
   */
  
  var server = http.createServer(function(req, res){
      var proxy = proxyServers.shift();
      proxy.web(req, res);
      proxyServers.push(proxy);
  });
  
  /**
   * Listen on provided port, on all network interfaces.
   */
  server.listen(port, function(){console.log("server is listening on port " + port);});
  server.on('error', onError);
  server.on('listening', onListening);
  </code></pre>
  
  <p>My problem: </p>
  
  <p>If one of my servers (for example port 3002) is not started or has an error, how can I automatically redirect requests to the other available server (i.e. port 3001)?</p>