Hosting Angular 2 application with Django rest framework backend API

February 10, 2017 2.7k views
Django Deployment API Ubuntu 16.04

I want to be able to host my angular 2 website that using a Django rest framework API. I followed this tutorial to host a django app https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 But how will I be able to host the angular app and django rest framework app?

1 Answer
jtittle February 10, 2017
Accepted Answer

@marcduplessis1

The guide mentioned covers handling the setup of your Django app. To setup another, you'd need to setup another server block to handle your Angular application/website. How you'd go about doing it depends on app-specific needs.

If the Angular application runs on port, similar to how your Django app does, then you could simply setup another server block with a proxy, similar to what was used in the guide, but substituting your Angular app details in place.

Example

Pulling the server block from the Django guide and using it as a base example, as shown below.

server {
    listen 80;
    server_name domain.com www.domain.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/myproject;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
    }
}

Now, if you're Angular application uses http://localhost:2356 (as an example), you could copy that over to a new server block and simply change out the proxy_pass line as well as server_name.

server {
    listen 80;
    server_name domain2.com www.domain2.com;

    location / {
        include proxy_params;
        proxy_pass http://localhost:2356;
    }
}

Alternatively, if you wanted to serve them both from the same block, you could. Let's say the URL for your Django API is:

http://domain.com/api

and your website, of course, would be domain.com, you could use something such as:

server {
    listen 80;
    server_name domain.com www.domain.com;

    # Handles proxying to Angular App
    location / {
        include proxy_params;
        proxy_pass http://localhost:2356;
    }

    # Handles proxying to Django API
    location /api {
        include proxy_params;
        proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
    }
}

It all depends on your application specific needs and how you want to set things up. These are just a few examples.

Have another answer? Share your knowledge.