Skip to main content

How To Serve Angular Application With NGINX and Docker

 There are so many ways we can build Angular apps and ship for production. One way is to build Angular with NodeJS or Java and another way is to build the angular and serve that static content with NGINX web server. When we build with NGINX and docker we don’t have to deal with server runtime or server related code. All we need to build the Angular app for prod and serve the generated static content with the NGINX server.

In this post, we will see the details and implementation of the second approach. We will go through step by step with an example.

Introduction

In this project, we are going to use Angular as a JS framework, NGINX as a web server, docker as a container runtime.

Image for post
NGINX serving static files

If we look at the above diagram, Angular builds the app and place the static assets in the /dist folder. We place these assets in the NGINX default location /usr/share/nginx/htmlwhere it serves the web content from.

Prerequisites

There are some prerequisites to accomplish this task. We have to run NGINX in the docker and place the static assets in the NGINX and run the whole setup inside the docker. We need to install nodejs for the API setup. Please install all the below tools to follow along with this tutorial or you want to run this on your machine.

Example Project

This is a simple project which demonstrates serving static Angular application with NGINX and Docker. We have a simple app with a table which gets some data from the server.

Image for post
Sample Angular App

Here is the example project where you can clone and run on your machine

// clone the project
git clone https://github.com/bbachi/angular-nginx-docker.git
// install and start the dependencies
npm install
npm start
// build the docker image
docker build -t appui .
// run the app
docker run -d --name appui -p 80:80 appui

This is a simple Angular app that shows the table and gets the data app.config.json from the assets folder of the application. Here are the app.component.html and app.component.ts files.

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<div class="tblclas">
  <h2>Environment Configuration </h2>
  <table *ngIf="appData" class="table table-striped">
    <thead class="thead-dark">
      <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Version</th>
        <th scope="col">Environment</th>
        <th scope="col">Base HREF</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let data of appData; let i = index">
        <th scope="row">{{i}}</th>
        <td>{{data.name}}</td>
        <td>{{data.version}}</td>
        <td>{{data.environment}}</td>
        <td>{{data.basehref}}</td>
      </tr>
    </tbody>
  </table>
</div>

import { Component } from '@angular/core';
import { AppService } from './app.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'envapp';
  appData: any;

  constructor(private appService: AppService) {
      this.appService.getConfig().subscribe(data => {
          this.appData = data;
      })
  }
}


Here is the service file which reads the app.config.json file from the assets folder.

[
    {
        "name": "envapp",
        "version": "1.0.0",
        "environment": "development",
        "basehref": "envapp"
    },
    {
        "name": "envapp",
        "version": "1.0.0",
        "environment": "test",
        "basehref": "envapp"
    },
    {
        "name": "envapp",
        "version": "1.0.0",
        "environment": "uat",
        "basehref": "envapp"
    },
    {
        "name": "envapp",
        "version": "1.0.0",
        "environment": "production",
        "basehref": "envapp"
    }
]




import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor(private http: HttpClient) { }

  configUrl = 'envapp/assets/app.config.json';

  getConfig() {
    return this.http.get(this.configUrl);
  }
}

Just Enough NGINX For This Project

We are not going through everything about NGINX here and we just go through just enough for this project. If you are already familiar with this stuff, you can skip over to the next section.

NGINX processes are divided into one master process and several worker processes. The master process takes care of evaluating configuration and maintaining worker processes and the worker processes take care of actual requests. We can define the number of worker processes in the configuration file which can be placed in the directory /usr/local/etc/nginx, /etc/nginx or /usr/local/nginx/conf.

The configuration file consists of directives that form the modules or contexts. There are two kinds of directives: simple directives and block directives. A simple directive has names and parameters separated by a space and ends with a semicolon like this listen 80; . A block directive is the same but has additional information and surrounded by braces like this { listen 80; root /usr/share/nginx/html; }.

Let’s understand the NGINX configuration file that we used in this project. Below is the  file which is located under folder  at root location of the project.

Everything is a context in the configuration file. We have a hierarchical context that starts with the main context. For example, worker_processes and events are defined in the main context and another context starts with http. We have another context inside http called server which listens on port 80 and serving static assets from the root location /usr/share/nginx/html.

We can have multiple declarations of the server inside the http context and we can have multiple declarations of location inside the server context.

nginx.conf


worker_processes 4;

events { worker_connections 1024; }

http {
    server {
        listen 80;
        root  /usr/share/nginx/html;
        include /etc/nginx/mime.types;

        location /appui {
            try_files $uri /envapp/index.html;
        }
    }
}


Implementation

We use Docker as a container runtime for this project. We are using multi-stage builds to build the Docker image. Here is the Dockerfile for the project.

# stage1 as builder
FROM node:10-alpine as builder

# copy the package.json to install dependencies
COPY package.json package-lock.json ./

# Install the dependencies and make the folder
RUN npm install && mkdir /app-ui && mv ./node_modules ./app-ui

WORKDIR /app-ui

COPY . .

# Build the project and copy the files
RUN npm run ng build -- --deploy-url=/envapp/ --prod


FROM nginx:alpine

#!/bin/sh

COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf

## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*

# Copy from the stahg 1
COPY --from=builder /app-ui/dist /usr/share/nginx/html

EXPOSE 4200 80

ENTRYPOINT ["nginx", "-g", "daemon off;"]


Stage 1

We are using node:10-alpine as a base image for the stage1 and copying package.json to install all the dependencies. We then copy the remaining project later, in that way we can skip the installing dependencies every time there is a change in the files. Docker uses cache to build the image from existing layers if there is no change.

We build the project with the deploy-url with /envapp/ and all the built static files are placed in the /dist folder.

Stage 2

Stage 2 starts with the base image nginx:alpine and copy the nginx.conf file, remove the index file from the root location, and finally, copy all the files from stage 1 to the root location where it can serve the content from.

Build the Image and Run the Project

Let’s build the project with this command docker build -t app-ui . and you can run the project with this command docker run -d --name -p 80:80 app-ui . You can run the app on http://localhost:80/appui


Important Things to notice

The container port and nginx listen port should be the same which is 80 otherwise you would get ERR_EMPTY_RESPONSE when you run the project.

// container port
docker run -d --name appui -p 80:80 appui
// nginx confhttp { server {
listen 80;
}
}

We should include this directive in the nginx.conf file otherwise all the styles are rendered as plain text in the browser.

include /etc/nginx/mime.types;

Exec Into the Running Container

While the container is in running state we can exec into it and see the contents of the file system.

docker exec -it appui /bin/sh

We can actually see all the contents under /usr/share/nginx/html

Image for post
File system inside docker

Summary

  • NGINX can be used as a web server or reverse proxy to serve the static content.
  • All the NGINX configuration can be placed in this file nginx.conf .
  • We need to build the angular app and place all the static files in the root location of the NGINX to serve the web.
  • Docker is used as the container runtime.
  • We use multi-stage builds to reduce the final image size and remove unnecessary files from the production environment.
  • Docker image can be built with docker build -t app-ui .
  • Run the container with this command docker run -d --name appui -p 80:80 app-ui.
  • It’s very important to match ports while running the container and the listen port in nginx.conf file. Otherwise, you would get an ERR_EMPTY_RESPONSE error.
  • You can exec into the container to explore the file system with this command docker exec -it appui /bin/sh.








Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...