The 92% chunk asset optimisation problem nodejs Angular5

At times running Angular Application on an environment which is fresh can be daunting. We may end up with errors which are not in alignment towards the development. One such of a case is the 92% chunk asset optimization problem when running a build of the Angular application.

On AWS hooked up an ec2-instance with Ubuntu 16.04, every thing works fine until you run the command npm run build.

We are stuck in an exception, 92% chunk asset optimisation and the dist directory is not created. Though we end up looking information on the development stack, but at times it could also be related to the Operating System SWAP space.

If the SWAP space on the OS if short or not available, this error shows up and to go around the error follow the instructions to check and allocate swap space on ubuntu. Hopefully this should help in getting around the problem.

One of the easiest way of increasing the responsiveness of your server and guarding against out of memory errors in your applications is to add some swap space. Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.

Basically, this gives you the ability to increase the amount of information that your server can keep in its working “memory”, with some caveats. The space on the hard drive will be used mainly when space in RAM is no longer sufficient for data.

The information written to disk will be slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fall back for when your system’s RAM is depleted is a good safety net.

sudo swapon -s

Another command for the same thing

free -m

Before we do this, we should be aware of our current disk usage. We can get this information by typing:

df -h

Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point.

Since my system has 4 Gigabytes of RAM, and doubling that would take a significant chunk of my disk space that I’m not willing to part with, I will create a swap space of 4 Gigabytes to match my system’s RAM.

Creating SWAP File
sudo fallocate -l 4G /swapfile
Check by running the following command that the SWAP file was created and space was reserved
ls -lh /swapfile
Enable SWAP Fiile
sudo mkswap /swapfile
Verfiy Permissions are set correctly
ls -lh /swapfile
Now that our file is more secure, we can tell our system to set up the swap space by typing:
sudo swapon /swapfile

We can verify that the procedure was successful by checking whether our system reports swap space now:

sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        4194300 0       -1

We have a new swap file here. We can use the free utility again to corroborate our findings:

free -m

https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04

Setting up a Reverse Proxy Server

Following our previous Process Manager for Nodejs Applications,  article, here we would get to see a walk through of how to set up a reverse proxy server for our nodejs application,

Now that our nodejs application is running, and listening on a private IP address, we need to set up a way where end users  access it. We will set up an Nginx web server as a reverse proxy. This tutorial will set up an Nginx server from scratch.

On the web server, let’s update the apt-get package lists with this command:

  • sudo apt-get update

Then install Nginx using apt-get:

  • sudo apt-get install nginx

Now open the default server block configuration file for editing:

  • sudo vi /etc/nginx/sites-available/default

Delete everything in the file and insert the following configuration. Be sure to substitute your own domain name for the server_name directive (or IP address if you don’t have a domain set up), and the app server private IP address for the APP_PRIVATE_IP_ADDRESS. Additionally, change the port (8080) if your application is set to listen on a different port:

/etc/nginx/sites-available/default
server {
    listen 80;

    server_name example.com;

    location / {
        proxy_pass http://APP_PRIVATE_IP_ADDRESS:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

This configures the web server to respond to requests at its root. Assuming our server is available at example.com, accessing http://example.com/ via a web browser would send the request to the application server’s private IP address on port 8080, which would be received and replied to by the Node.js application.

You can add additional location blocks to the same server block to provide access to other applications on the same web server. For example, if you were also running another Node.js application on the app server on port 8081, you could add this location block to allow access to it via http://example.com/app2:

Nginx Configuration — Additional Locations
    location /app2 {
        proxy_pass http://APP_PRIVATE_IP_ADDRESS:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

Once you are done adding the location blocks for your applications, save and exit.

On the web server, restart Nginx:

  • sudo service nginx restart

Assuming that your Node.js application is running, and your application and Nginx configurations are correct, you should be able to access your application via the reverse proxy of the web server. Try it out by accessing your web server’s URL (its public IP address or domain name).

 

 

Process Manager for Nodejs Applications

In our last article where in we created our first application on nodejs, we mentioned the fact that we cannot stop the nodejs application once started if we want to service requests. While it can turn out to be pretty difficult to start and stop, if we are going to have multiple nodejs applications running.

With Process Manager we can manage & daemonize all the nodejs applications. PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. Refer https://www.npmjs.com/package/pm2

To install PM, we will be using NPM (Node Packaged Modules) which is basically a Package Manager for Node Modules. This is installed by default with nodejs.

To install PM on our app server issue the following command

user@LT-201:~/projects/trials/nodejstrials$ sudo npm install pm2 -g
[sudo] password for user:
/usr/local/bin/pm2 -> /usr/local/lib/node_modules/pm2/bin/pm2
/usr/local/bin/rundev -> /usr/local/lib/node_modules/pm2/bin/rundev
/usr/local/bin/pm2-dev -> /usr/local/lib/node_modules/pm2/bin/pm2-dev
/usr/local/bin/pm2-docker -> /usr/local/lib/node_modules/pm2/bin/pm2-docker
/usr/local/lib
`– pm2@2.4.2
+– async@1.5.2
+– blessed@0.1.81
+– chalk@1.1.3
| +– ansi-styles@2.2.1
| +– escape-string-regexp@1.0.5
| +– has-ansi@2.0.0

To start the application in the back ground,  using PM2, it also adds your application to PM2’s process list, which is shown every time you start an application:


user@LT-201:~/projects/trials/nodejstrials$ pm2 start hello.js

————-

PM2 process manager

__/\\\\\\\\\\\\\____/\\\\____________/\\\\____/\\\\\\\\\_____
_\/\\\/////////\\\_\/\\\\\\________/\\\\\\__/\\\///////\\\___
_\/\\\_______\/\\\_\/\\\//\\\____/\\\//\\\_\///______\//\\\__
_\/\\\\\\\\\\\\\/__\/\\\\///\\\/\\\/_\/\\\___________/\\\/___
_\/\\\/////////____\/\\\__\///\\\/___\/\\\________/\\\//_____
_\/\\\_____________\/\\\____\///_____\/\\\_____/\\\//________
_\/\\\_____________\/\\\_____________\/\\\___/\\\/___________
_\/\\\_____________\/\\\_____________\/\\\__/\\\\\\\\\\\\\\\_
_\///______________\///______________\///__\///////////////__

Getting started

Documentation
http://pm2.io/

Start PM2 at boot
$ pm2 startup

Daemonize Application
$ pm2 start <app>

Monitoring/APM solution
https://app.keymetrics.io/

————-

[PM2] Spawning PM2 daemon with pm2_home=/home/user/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /home/user/projects/trials/nodejstrials/hello.js in fork_mode (1 instance)
[PM2] Done.
┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────────┐
│ App name │ id │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ watching │
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────────┤
│ hello    │ 0  │ fork │ 14796 │ online │ 0       │ 0s     │ 9%  │ 21.3 MB   │ disabled │
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────────┘
Use `pm2 show <id|name>` to get more details about an app

To stop an application

user@LT-201:~/projects/trials/nodejstrials$ pm2 stop hello.js
[PM2] Applying action stopProcessId on app [hello.js](ids: 0)
[PM2] [hello](0) ✓
┌──────────┬────┬──────┬─────┬─────────┬─────────┬────────┬─────┬────────┬──────────┐
│ App name │ id │ mode │ pid │ status  │ restart │ uptime │ cpu │ mem    │ watching │
├──────────┼────┼──────┼─────┼─────────┼─────────┼────────┼─────┼────────┼──────────┤
│ hello    │ 0  │ fork │ 0   │ stopped │ 0       │ 0      │ 0%  │ 0 B    │ disabled │
└──────────┴────┴──────┴─────┴─────────┴─────────┴────────┴─────┴────────┴──────────┘
Use `pm2 show <id|name>` to get more details about an app

Information about an application can be found at

user@LT-201:~/projects/trials/nodejstrials$ pm2 info hello.js

To restart application

user@LT-201:~/projects/trials/nodejstrials$ pm2 restart hello.js

To PM2 process monitor can be viewed using the following command

user@LT-201:~/projects/trials/nodejstrials$ pm2 monit

 

Applications that are running under PM2 will be restarted automatically if the application crashes or is killed, but an additional step needs to be taken to get the application to launch on system startup (boot or reboot). Luckily, PM2 provides an easy way to do this, the startup subcommand.

The startup subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots. You must also specify the platform you are running on, which is ubuntu, in our case:

  • pm2 startup ubuntu

The last line of the resulting output will include a command (that must be run with superuser privileges) that you must run:

Output:
[PM2] You have to run this command as root
[PM2] Execute the following command :
[PM2] sudo su -c "env PATH=$PATH:/opt/node/bin pm2 startup ubuntu -u sammy --hp /home/sammy"

Run the command that was generated (similar to the highlighted output above) to set PM2 up to start on boot (use the command from your own output):

  • sudo su -c “env PATH=$PATH:/opt/node/bin pm2 startup ubuntu -u sammy –hp /home/sammy”
 Move to the next article to get to learn How to Setup a Reverse Proxy Server

My First Node.js Application

This article is in continuation to the Nodejs Series. To refer how to install Nodejs on Ubuntu follow the link Setting up Nodejs Environment on Ubuntu

Hello world application that returns “Hello World” to any HTTP requests.

Move to your projects directory

user@LT-201: mkdir /projects/trials/nodejstrials

create a helloworld.js using the vi editor

user@LT-201:vi helloworld.js

Write the code to return a Hello World string with a 200 Status Response

var http=require(‘http’);
http.createServer( function (req,res) {
res.writeHead(200,{‘Content-type’: ‘text/plain’});
res.end(‘Hello World\n’);
}).listen(8080, ‘127.0.0.1’);
console.log(‘Server running at http://127.0.0.1:8080’);

The nodejs application simply listens to a particular port on a given IP Addreess. On receiving a request on that IP Address and Port, it simply returns the response Hello World with a 200 status code.

user@LT-201:~/projects/trials/nodejstrials$ node -v
v6.10.0

To test the application which has been written issue the following node command on the app server. The command starts the Nodejs Server at the configured IP Address and Port #
user@LT-201:~/projects/trials/nodejstrials$ node hello.js
Server running at http://127.0.0.1:8080

While the app server is running, we cannot issue any new node commands until we break it using CTRL + C

To test the application from a web server, issue a curl command from a new terminal

user@LT-201:~$ curl http://127.0.0.1:8080
Hello World

In case if you stop the nodejs application and then issue a curl command in the other terminal

user@LT-201:~$ curl http://127.0.0.1:8080
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused

In the next article we would see to how to configure NPM

How to set up Nodejs for development and production environments on Ubuntu 16.04

Node.js is a Javascript platform for server-side programming that allows users to build network applications quickly. By leveraging Javascript on both the front-end and the back-end, development can be more consistent and be designed within the same system.

NPM: makes it easy to share and reuse Javascript code. The bits of reusable code are called packages or modules. A package is a directory with one or more files in it which has a file called ‘package.json’ which is the meta-data of the package. Nodejs comes with NPM installed.

The following steps would help to install nodejs on a development machine.

To install nodejs directly on the Ubuntu using the debian packages

sudo apt-get update
sudo apt-get install nodejs
locate nodejs
whereis nodejs

To uninstall or remove nodejs in Ubuntu

dpkg -l
dpkg purge nodejs
dpkg  –remove

dpkg -l nod*

sudo apt-get purge nodejs
sudo apt-get purge –auto-remove nodejs
sudo apt-get purge nodejs
sudo apt-get autoremove

Though it is a quick way to install nodejs using package on Ubuntu, but not the preferred one, to have a more controlled installation where in multiple versions of nodejs can co-exist, it is better to install in the opt directory using the tar files.

Two approaches which can be thought off during deployment

app: nodejs application and runtime would be there on one server, and the end users would be using this server IP address to access the nodejs application

web:NGINX web server which would serve as front end for end users to make requests. This server would act as a reverse proxy to the nodejs application. End users would access this NGINX IP Address to access the nodejs application

If only one server is preferred, for the remaining part of the tutorial just replace the IP Address with localhost/127.0.0.1

A simple deployment illustration of nodejs where in the web server could be a NGINX web server which would serve as front end for end users to make requests. This server would act as a reverse proxy to the nodejs application. End users would access this NGINX IP Address to access the nodejs application.

 

Reverse Proxy to Node.js Application

Download the latest nodejs from for Linux

user@LT-201:~/Downloads$ wget https://nodejs.org/dist/v6.10.0/node-v6.10.0-linux-x64.tar.xz
–2017-03-05 13:59:50–  https://nodejs.org/dist/v6.10.0/node-v6.10.0-linux-x64.tar.xz
Resolving nodejs.org (nodejs.org)… 104.20.22.46, 104.20.23.46, 2400:cb00:2048:1::6814:162e, …
Connecting to nodejs.org (nodejs.org)|104.20.22.46|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 9376372 (8.9M) [application/x-xz]
Saving to: ‘node-v6.10.0-linux-x64.tar.xz’

node-v6.10.0-linux- 100%[===================>]   8.94M  3.84MB/s    in 2.3s

2017-03-05 13:59:54 (3.84 MB/s) – ‘node-v6.10.0-linux-x64.tar.xz’ saved [9376372/9376372]

Create a directory to hold contents of the extracted archiv

user@LT-201:~/Downloads$ mkdir node
user@LT-201:~/Downloads$ tar xvf node-v*.tar.?z –strip-components=1 -C ./node //-C option is to Change Directory before performing any operation. –strip-components=1, specifies the number to strip components from files names on extraction.

Next, we’ll configure the global prefix of npm, where npm will create symbolic links to installed Node packages, to somewhere that it’s in your default path. We’ll set it to /usr/local with this command:

user@LT-201:~/Downloads$ mkdir node/etc //this creates a directory by name etc under node directory
user@LT-201:~/Downloads$ echo ‘prefix=/usr/local’ > node/etc/npmrc //this creates a a global prefix for npm, a file with name npmrc with global config

With all nodejs extracted, now we can move the nodejs and npm binaries to our installation location /opt/node with the following command

user@LT-201:~/Downloads$ sudo mv node /opt/

Make root as the owner of the files

user@LT-201:/opt$ sudo chown -R root: /opt/node

Then we move to create symbolic links of the node and npm binaries in the default path. We will put the links in /usr/local/bin with these commands

user@LT-201:/opt$ sudo ln -s /opt/node/bin/node /usr/local/bin/node
user@LT-201:/opt$ sudo ln -s /opt/node/bin/npm /usr/local/bin/npm

Verify the node is installed by checking

user@LT-201:/opt$ node -v
v6.10.0

The Node.js runtime is now installed, and ready to run an application! Let’s write a Node.js application.

Refer the next article in the series to create your first application