Wednesday, August 7, 2013

Running Django and Node.js on the Same Server Using Apache

I've recently started working with Node.js and have been coding a few projects that I wanted to host on my VPS. However, I already have a few sites that I've written in Django running on that server on port 80. As it turns out, it's not terribly difficult to run both Node and Django on the same server, with different domains, both utilizing port 80.

I'm going to assume that you've already installed Python, Django, and Node.js on your server and that you have working projects. There are tons of tutorials on installing these on a server, so I'm not going to use this space for that. So let's begin!

First, to create the Django site, upload your Django files to your server. I'm going to save them in the directory /user/web.

To get Django working, there is a great tutorial over at DigitalOcean here:

Make sure to follow all the steps. Once you can access and see your app, you are successful.

Apache is now serving your Django app via mod_wsgi. To serve the Node.js app, we're going to use a reverse proxy pointing to a running instance of the Node.js server on a different port (I'll be using 3000).

Upload all of your Node.js project files to your server. I'll be saving them in /user/web/node.

Now, enable the proxy with the following command:

sudo a2enmod proxy proxy_http

Next, create a file in /etc/apache2/sites-available for your domain such as: /etc/apache2/sites-available/

In this file, paste the following code, changing to your domain:

<VirtualHost *:80>

    ProxyRequests off

    <Proxy *>
        Order deny,allow
        Allow from all

    <Location />
        ProxyPass http://localhost:3000/
        ProxyPassReverse http://localhost:3000/

If you need to use another port, change both locations.

Save this file, and then start your node server on the port you specified. Add the site with the following command:

sudo a2ensite

Make sure to restart your Apache service:

sudo service apache2 restart

Now, when a user visits, Apache will call your Django app using mod_wsgi as described in the linked tutorial above. When you visit, Apache will use a reverse proxy to call the Node.js server running on the port you specified.

You can repeat this process to add as many Node.js projects as you want, but make sure you use a different port for each.

Additionally, I recommend using a Node tool called "forever" (npm install -g forever) to keep your service running in the background and restart it if it crashes.

1 comment: