Install Node.js and PM2 on AlmaLinux / RockyLinux

Install Node.js dan PM2 pada AlmaLinux / RockyLinux

  • Update repository
yum makecache && yum install epel-release -y && yum install nano unzip -y
  • Cek list versi nodejs
yum module list nodejs
---<output>---
Last metadata expiration check: 0:01:11 ago on Sat 24 Feb 2024 10:45:05 AM WIB.
AlmaLinux 8 - AppStream
Name                           Stream                         Profiles                                                      Summary
nodejs                         10 [d]                         common [d], development, minimal, s2i                         Javascript runtime
nodejs                         12                             common [d], development, minimal, s2i                         Javascript runtime
nodejs                         14                             common [d], development, minimal, s2i                         Javascript runtime
nodejs                         16                             common [d], development, minimal, s2i                         Javascript runtime
nodejs                         18                             common [d], development, minimal, s2i                         Javascript runtime
nodejs                         20                             common [d], development, minimal, s2i                         Javascript runtime

Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled
  • Install Node.js 20
yum module enable nodejs:20 -ynp
yum module install nodejs:20 -y
  • Cek versi Node.js dan NPM
npm -v
---<output>---
10.2.4

node -v
---<output>---
v20.11.0

  • Install PM2
npm install pm2@latest -g
npm fund
  • Cek status PM2
pm2 status
---<output>---
                        -------------

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

                          Runtime Edition

        PM2 is a Production Process Manager for Node.js applications
                     with a built-in Load Balancer.

                Start and Daemonize any application:
                $ pm2 start app.js

                Load Balance 4 instances of api.js:
                $ pm2 start api.js -i 4

                Monitor in production:
                $ pm2 monitor

                Make pm2 auto-boot at server restart:
                $ pm2 startup

                To go further checkout:
                http://pm2.io/
                        -------------

[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
┌────┬───────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name      │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
└────┴───────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

Pengujian

  • Download source code website untuk testing
wget https://sys-ops.id/installer/web-test.zip
unzip web-test.zip && cd web-test
  • Buat file dengan nama index.js di dalam folder web-test
  • Port yang akan digunakan untuk menjalankan node.js adalah port 8080
var http = require('http');
var fs = require('fs');
var path = require('path');
var port = 8080

http.createServer(function (request, response) {
    console.log('request ', request.url);

    var filePath = '.' + request.url;
    if (filePath == './') {
        filePath = './index.html';
    }

    var extname = String(path.extname(filePath)).toLowerCase();
    var mimeTypes = {
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.css': 'text/css',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpg',
        '.gif': 'image/gif',
        '.svg': 'image/svg+xml',
        '.wav': 'audio/wav',
        '.mp4': 'video/mp4',
        '.woff': 'application/font-woff',
        '.ttf': 'application/font-ttf',
        '.eot': 'application/vnd.ms-fontobject',
        '.otf': 'application/font-otf',
        '.wasm': 'application/wasm'
    };

    var contentType = mimeTypes[extname] || 'application/octet-stream';

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if(error.code == 'ENOENT') {
                fs.readFile('./404.html', function(error, content) {
                    response.writeHead(404, { 'Content-Type': 'text/html' });
                    response.end(content, 'utf-8');
                });
            }
            else {
                response.writeHead(500);
                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
            }
        }
        else {
            response.writeHead(200, { 'Content-Type': contentType });
            response.end(content, 'utf-8');
        }
    });

}).listen(port);

console.log('Server running at http://0.0.0.0:'+port);
  • Jalankan npm init untuk meng-generate file package.json
npm init --yes
  • Jalankan index.js dengan node
node index.js
---<output>---
Server running at http://0.0.0.0:8080
  • Alternatif menjalanakan index.js dengan npm
  • Edit file package.json > tambahkan script baru dengan nama web-test
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "web-test": "node index.js"
  },
  • Jalankan index.js dengan npm
npm run web-test
---<output>---
> [email protected] web-test
> node index.js

Server running at http://0.0.0.0:8080
  • Akses aplikasi web-test dengan url: http://ip_server:8080

  • Jalankan index.js dengan pm2 dengan nama instance web-test
pm2 start index.js --name web-test
---<output>---
[PM2] Starting /root/test/web-test/index.js in fork_mode (1 instance)
[PM2] Done.
┌────┬─────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name        │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├────┼─────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0  │ web-test    │ default     │ 1.0.0   │ fork    │ 360349   │ 0s     │ 0    │ online    │ 0%       │ 14.3mb   │ root     │ disabled │
└────┴─────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
  • Stop instance web-test
pm2 stop web-test
---<output>---
[PM2] Applying action stopProcessId on app [web-test](ids: [ 0 ])
[PM2] [web-test](0) ✓
┌────┬─────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name        │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├────┼─────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0  │ web-test    │ default     │ 1.0.0   │ fork    │ 0        │ 0      │ 0    │ stopped   │ 0%       │ 0b       │ root     │ disabled │
└────┴─────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
  • Delete instance web-test
pm2 del web-test
---<output>---
[PM2] Applying action deleteProcessId on app [web-test](ids: [ 0 ])
[PM2] [web-test](0) ✓
┌────┬───────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name      │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
└────┴───────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

herdiana3389

A system administrator with skills in system administration, virtualization, linux, windows, networking, cloud computing, container, etc.