[Fixed]-How to run Django and node.js app on same dyno in Heroku?

1πŸ‘

βœ…

The Error: listen EADDRINUSE error comes from calling .listen() twice with the same port in app.js.

You are on the right track. Here is an example of how to proxy /channel requests to a Node.JS app and all other requests to another app (a Django app in this case):

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

var NODE_PORT = 4711;

var proxy = httpProxy.createProxyServer({});

http.createServer(function(req, res) {
    // For all URLs beginning with /channel proxy to the Node.JS app, for all other URLs proxy to the Django app running on DJANGO_PORT
    if(req.url.indexOf('/channel') === 0) {
        // Depending on your application structure you can proxy to a node application running on another port, or serve content directly here
        proxy.web(req, res, { target: 'http://localhost:' + NODE_PORT });

        // Proxy WebSocket requests if needed
        proxy.on('upgrade', function(req, socket, head) {
            proxy.ws(req, socket, head, { target: 'ws://localhost:' + NODE_PORT });
        });
    } else {
        proxy.web(req, res, { target: 'http://localhost:' + process.env.DJANGO_PORT });
    }
}).listen(process.env.PORT);

// Example node application running on another port
http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('Request successfully proxied to Node.JS app');
    res.end();
}).listen(NODE_PORT);
πŸ‘€Aule

0πŸ‘

UPDATE: The solution in the link https://blog.heroku.com/heroku-django-node must be corrected.

Replace 127.0.0.0 with 0.0.0.0 in

django: gunicorn path.to.wsgi:application --bind 127.0.0.1:$DJANGO_PORT

For some reasons Heroku has issues with 127.0.0.1 or localhost.
See also https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error

While working on this setup be sure to have in Procfile.web both the lines

django: gunicorn path.to.wsgi:application --bind 127.0.0.1:$DJANGO_PORT
node: node server.js

because you are binding on $DJANGO_PORT, but it’s mandatory to bind something also on the default $PORT (here, the node server) as explained in https://devcenter.heroku.com/articles/dynos#web-dynos
otherwise you get the error

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

πŸ‘€fabiosalvi

Leave a comment