NodeJs createProxyServer Error: connect ECONNREFUSED 127.0.0.1

There is a serious a very random issue with NodeJs with ExpressJS and ‘http-proxy’. There is no proper sequence for this exception, it may come, may not come. For some people the issue is coming consistently, for some people issue is coming randomly.

Interesting observation is, this issue is appearing most of the time when we host the app in cloud platforms like Google GCP, Amazon AWS or Heroku. However we still have no proper answer for this, though the same question is asked multiple times in different Stack Over Flow Posts and other forums. below is the code which is causing the issue

<code>const express = require('express');
const path = require('path');
const logger = require('morgan');
const http = require('http');
//PROXY
const httpProxy = require('http-proxy');
const app = express();
app.use(express.static(path.join(__dirname, '../../../../build')));
app.use(express.static(path.join(__dirname, 'public')));
const apiProxy = httpProxy.createProxyServer();
app.use('/api', (req, res) => {
  console.log('---- api called ----');
  apiProxy.web(req, res, { target: `http://localhost:${process.env.API_PORT}` });
});


  function normalizePort(val) {
    const port = parseInt(val, 10);

    if (isNaN(port)) {
      // named pipe
      return val;
    }

    if (port >= 0) {
      // port number
      return port;
    }

    return false;
  }
  
  /**
   * Get port from environment and store in Express.
   */
  const port = normalizePort(process.env.PORT || 8080);
  console.log('--- client port --- ', port);
  app.set('port', port);

  // app.get('*.js', function (req, res, next) {
  //   console.log('---- ** returning gz');
  //   req.url = req.url + '.gz';
  //   res.set('Content-Encoding', 'gzip');
  //   next();
  // });

  /**
   * Create HTTP server.
   */

  const server = http.createServer(app);

  /**
   * Event listener for HTTP server "error" event.
   */

  function onError(error) {
    if (error.syscall !== 'listen') {
      throw error;
    }

    const bind = typeof port === 'string'
      ? 'Pipe ' + port
      : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  }

  /**
   * Event listener for HTTP server "listening" event.
   */

  function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  }
  /**
   * Listen on provided port, on all network interfaces.
   */

  server.listen(port);
  server.on('error', onError);
  server.on('listening', onListening);
</code>

Exception Occurred is Error: connect ECONNREFUSED 127.0.0.1:4001

complete error printed in console is as follows

<code>A 2021-01-27T09:44:46Z npm ERR!     /root/.npm/_logs/2021-01-27T09_44_46_065Z-debug.log
 
A 2021-01-27T09:44:46Z npm ERR! A complete log of this run can be found in:
 
A 2021-01-27T09:44:46Z 
 
A 2021-01-27T09:44:46Z npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
 
npm ERR! Failed at the yourApp@0.1.0 start script.
 
npm ERR! 
 
npm ERR! Exit status 1
 
npm ERR! sociallygood@0.1.0 start: `node src/server/apiServer &amp; node bin/www`
 
npm ERR! errno 1
 
npm ERR! code ELIFECYCLE
 
Error: connect ECONNREFUSED 127.0.0.1:4001
    at TCPConnectWrap.afterConnect &#91;as oncomplete] (net.js:1106:14)
 
  undefined
</code>