Serving Angular App from behind a NGINX web-server.

I recently worked on a project to deploy an Angular App on an Embedded Device running Poky Linux Distribution. I was not able to find many references on how to set up the Nginx server to serve an Angular (or React/VueJS app). This document is a provides step-by-step overview of what was needed to set this up.

Serving Angular Application from a Nginx server

Let’s start with the Angular App. First step is to compile your Angular App into a set of plain HTML/Javascript/CSS files. For Angular application created using Angular-CLI (@angular/cli) this can be done with “ng build --prod” command.

For Angular applications, a production build already includes several optimizations like ahead-of-time optimizations, and Javascript/CSS minimization; so the above build command is sufficient for most use-cases.

The command above would create a dist directory which can be rendered directly from the nginx server. Following screenshot shows sample contents of the dist directory.

Angular production build (dist directory) contents

The next part is serving it through Nginx server — and this requires edits to the Nginx configuration file.

On a Mac OSX: Installing and starting Nginx server involves the following steps:

$ brew install nginx
$ sudo nginx

The nginx server would now be running at localhost:8080, and the Nginx configuration file is available at: /usr/local/etc/nginx/nginx.conf

On a Ubuntu machine: following steps are required to start Nginx server:

$ sudo apt-get install nginx

To start/stop/restart Nginx server on a Ubuntu Server, use the following commands:

$ sudo /etc/init.d/nginx start
$ sudo /etc/init.d/nginx stop
$ sudo /etc/init.d/nginx restart

The Nginx configuration file is available at /usr/local/etc/nginx/nginx.conf for Mac OSX; and at /etc/nginx/nginx.conf for Ubuntu.

Edit the nginx.conf file to create an entry for the Angular Application. Copy the dist directory into /var/www/<site-name>

In the example below, I have copied the dist directory into /var/www/angular-deploy

http {
...
server {
listen 8080;
server_name localhost;
location / {
root /var/www/angular-deploy;
index index.html index.htm;
}

Voila! That’s it! Now, open up localhost:8080 and you should be able to see your Angular Application deployed through Nginx.

Happy Hacking!


My name is Harsh Murari and I am a Software Developer working at Rhoynar Software Consulting (www.rhoynar.com). We provide custom software development services including, web/mobile development, Embedded/IoT platforms developments and QA Automation and DevOps. If you want to contact and/or hire me, send me a mail at: contact@rhoynar.com.