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
Prerequisites
Example Project
Just Enough NGINX For This Project
Implementation
Summary
Conclusion
Introduction
In this project, we are going to use Angular as a JS framework, NGINX as a web server, docker as a container runtime.
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.
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.
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>
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 nginx.conf file which is located under folder .nginx 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.
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
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.
Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts. Ngx-charts is one of them. Check out the list of best angular chart libraries . In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts is an open-source and declarative charting framework for angular2+. It is maintained by Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...
forRoot / forChild is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how forRoot() works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You inject the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...
During the automation of multiple tasks on my job and personal projects, i decided to move on Puppeteer instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ; COPY SNIPPET The setDefaultNav...
Comments
Post a Comment