---
title: "Spawning multiple TCP daemons in a single app"
date: "2016-01-13"
category: "node"
slug: "spawning-multiple-tcp-daemons-in-a-single-app"
---

Node applications can bind to a TCP port using `[listen](https://nodejs.org/api/net.html#net_server_listen_port_hostname_backlog_callback)(<PORT NUMBER>)`, provided the port is one [[listening-ports]] allocated to your account. Passenger replaces this `listen()` method with a [built-in method](https://github.com/phusion/passenger/blob/stable-5.0/src/helper-scripts/node-loader.js) that creates a local UNIX socket instead of a TCP port for communication with the web server.

This is beneficial for security, but if your app spawns another process (such as [Socket.IO](https://www.npmjs.com/package/socket.io)) that also calls `listen()`, the app will fail with:

> App 28096 stderr: Error: http.Server.listen() was called more than once, which is not allowed because Phusion Passenger is in auto-install mode. This means that the first http.Server object for which listen() is called, is automatically installed as the Phusion Passenger request handler. If you want to create and listen on multiple http. Server object then you should disable auto-install mode.

## Cause

Passenger overwrites `listen()` to create a UNIX socket instead of a TCP socket. This eliminates the need for a proxy passthrough but limits each application to a single `listen()` call.

## Solution

Disable Passenger's automatic `listen()` override using `autoInstall: false`, then use the special `"passenger"` port to create a UNIX socket for the primary application. Any additional daemons can use their own TCP ports as normal:

var http = require('http'),
 httpProxy = require('http-proxy');

// disable implicit listen() overwrite
if (typeof(PhusionPassenger) != 'undefined') {
 PhusionPassenger.configure({ autoInstall: false });
}

// explicitly listen on a Passenger socket for communication with the
// web server
httpProxy.createServer(9000, 'localhost').listen('passenger');

// create a second server on port 9000; this port should be a port
// allocated to your account
var target\_server = http.createServer(function (req, res) {
 res.writeHead(200, { 'Content-Type': 'text/plain' });
 res.write('request successfully proxied!' + '\\n' + JSON.stringify(req.headers, true, 2));
 res.end();
}).listen(9000);

## See Also

- [Phusion Passenger Error: http.Server.listen() was called more than once](http://stackoverflow.com/questions/20645231/phusion-passenger-error-http-server-listen-was-called-more-than-once/20645549) (StackOverflow)
