PM2, també anomenat "Mòdul de Gestió de Processos", és un gestor de processos que s'utilitza per gestionar aplicacions en Node.js. És gratuït, de codi obert i té un equilibrador de càrrega incorporat. Reinicia automàticament el servidor Node.js quan un procés deixa de funcionar. És multiplataforma i es pot executar en Windows, Linux i macOS. Et permet executar l'aplicació Node.js en mode de clúster sense fer cap canvi en el codi.
En aquest tutorial et mostrem com executar i administrar aplicacions Node.js utilitzant PM2.
Requisits previs
- Un servidor que executi Ubuntu 20.04.
- Una contrasenya root configurada al servidor.
Instal·la Node.js
Abans de començar, has d'instal·lar Node.js al teu servidor. Primer, afegeix el repositori d'origen de Node amb l'ordre següent:
# curl -sL https://deb.nodesource.com/setup_14.x | bash - Després, instal·la Node.js amb l'ordre següent:
# apt-get install nodejs -yUn cop s'hagi completat la instal·lació, verifica la versió de Node.js utilitzant l'ordre que indiquem més avall:
# node --versionHauries d'obtenir el resultat següent:
v14.17.1Crea una aplicació de mostra de Node.js
Per a aquest tutorial, hauràs de crear una aplicació de mostra de Node.js.
Primer, crea un directori per a la teva aplicació amb l'ordre següent:
# mkdir myappPer continuar, crea una aplicació hello.js amb l'ordre següent:
# nano myapp/hello.jsAfegeix les línies següents:
const http = require('http');
const hostname = 'your-server-ip';
const port = 8000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('This is My First Nodejs App!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});Recorda que has de canviar 'your-server-ip' per la IP pública del servidor. Desa i tanca el fitxer quan hagis acabat.
També hauràs d'obrir el port 8000 al tallafoc del teu servidor.
Instal·la PM2
Pots instal·lar PM2 fàcilment utilitzant l'ordre NPM tal com es mostra més avall:
# npm i -g pm2 Un cop PM2 estigui instal·lat, inicia la teva aplicació utilitzant PM2:
# pm2 start myapp/hello.jsHauries de veure el resultat següent:
__/\\\\\\\\\\\\\____/\\\\____________/\\\\____/\\\\\\\\\_____
_\/\\\/////////\\\_\/\\\\\\________/\\\\\\__/\\\///////\\\___
_\/\\\_______\/\\\_\/\\\//\\\____/\\\//\\\_\///______\//\\\__
_\/\\\\\\\\\\\\\/__\/\\\\///\\\/\\\/_\/\\\___________/\\\/___
_\/\\\/////////____\/\\\__\///\\\/___\/\\\________/\\\//_____
_\/\\\_____________\/\\\____\///_____\/\\\_____/\\\//________
_\/\\\_____________\/\\\_____________\/\\\___/\\\/___________
_\/\\\_____________\/\\\_____________\/\\\__/\\\\\\\\\\\\\\\_
_\///______________\///______________\///__\///////////////__
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
[PM2] Starting /root/myapp/hello.js in fork_mode (1 instance)
[PM2] Done.
┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │
├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0 │ hello │ default │ N/A │ fork │ 2788 │ 0s │ 0 │ online │ 0% │ 28.0mb │ root │ disabled │
└─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴───────Com utilitzar PM2
Per llistar totes les teves aplicacions en execució amb Node.js, fes-ho amb l'ordre següent:
# pm2 listHauries d'obtenir el resultat següent:
┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │
├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0 │ hello │ default │ N/A │ fork │ 2788 │ 26s │ 0 │ online │ 0% │ 37.5mb │ root │ disabled │
└─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
Per reiniciar l'aplicació, utilitza l'ordre següent:
# pm2 restart myapp/hello.jsPer iniciar la teva aplicació amb Node.js en mode de clúster, fes-ho amb l'ordre següent:
# pm2 start myapp/hello.js -i 2Hauries de veure el resultat següent:
[PM2] Starting /root/myapp/hello.js in cluster_mode (2 instances)
[PM2] Done.
┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │
├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0 │ hello │ default │ N/A │ cluster │ 3228 │ 0s │ 0 │ online │ 0% │ 35.6mb │ root │ disabled │
│ 1 │ hello │ default │ N/A │ cluster │ 3235 │ 0s │ 0 │ online │ 0% │ 30.0mb │ root │ disabled │
└─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
Per monitorar la teva aplicació, utilitza l'ordre següent:
# pm2 monitHauries de veure la pantalla següent:
Per comprovar els registres de l'aplicació, fes-ho amb l'ordre següent:
# pm2 logs Hauries d'obtenir el resultat següent:
/root/.pm2/logs/hello-error-0.log last 15 lines:
/root/.pm2/logs/hello-out-0.log last 15 lines:
0|hello | Server running at http://your-server-ip:8000/
/root/.pm2/logs/hello-out-1.log last 15 lines:
1|hello | Server running at http://your-server-ip:8000/
Per eliminar tots els registres, utilitza l'ordre següent:
# pm2 flushPer mostrar informació detallada de la teva aplicació, utilitza l'ordre següent:
# pm2 show 0Hauries de veure la pantalla següent:
Gestiona l'aplicació Node.js amb PM2
Per iniciar la teva aplicació Node.js amb un reinici del sistema, utilitza l'ordre següent:
# pm2 startupHauries de veure el resultat següent:
[ 'systemctl enable pm2-root' ]
[PM2] Writing init configuration in /etc/systemd/system/pm2-root.service
[PM2] Making script booting at startup...
[PM2] [-] Executing: systemctl enable pm2-root...
Created symlink /etc/systemd/system/multi-user.target.wants/pm2-root.service → /etc/systemd/system/pm2-root.service.
[PM2] [v] Command successfully executed.
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save
[PM2] Remove init script via:
$ pm2 unstartup systemd
Per eliminar el procés d'inici amb un reinici, fes-ho amb l'ordre següent:
# pm2 unstartupPer desar el procés d'inici amb un reinici del sistema, fes-ho amb l'ordre següent:
# pm2 savePer actualitzar PM2, utilitza l'ordre següent:
# pm2 updateHauries d'obtenir el resultat següent:
Be sure to have the latest version by doing `npm install pm2@latest -g` before doing this procedure.
[PM2] Applying action deleteProcessId on app [all](ids: [ 0, 1 ])
[PM2] [hello](0) ✓
[PM2] [hello](1) ✓
[PM2] [v] All Applications Stopped
[PM2] [v] PM2 Daemon Stopped
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] Restoring processes located in /root/.pm2/dump.pm2
[PM2] Process /root/myapp/hello.js restored
[PM2] Process /root/myapp/hello.js restored
>>>>>>>>>> PM2 updated
┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │
├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0 │ hello │ default │ N/A │ cluster │ 3445 │ 0s │ 0 │ online │ 0% │ 37.9mb │ root │ disabled │
│ 1 │ hello │ default │ N/A │ cluster │ 3446 │ 0s │ 0 │ online │ 0% │ 37.9mb │ root │ disabled │
└─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
Per aturar tots els processos de Node.js, utilitza l'ordre següent:
# pm2 stop all Per aturar el procés de Node.js amb id 0, fes-ho amb l'ordre següent:
# pm2 stop 0Per reiniciar tots els processos de l'aplicació de Node.js, utilitza l'ordre següent:
# pm2 restart all Per eliminar tots els processos, fes-ho amb l'ordre següent:
# pm2 delete all Per eliminar un procés amb id 1, fes-ho amb l'ordre següent:
# pm2 delete 1Accedeix a l'aplicació de Node.js
Ara obre el teu navegador web i accedeix a la teva aplicació de Node.js amb l'URL http://your-server-ip:8000. Hauries de veure la teva aplicació a la imatge següent:
Conclusió
Amb aquest tutorial has après com instal·lar i utilitzar PM2 per gestionar l'aplicació amb Node.js.
Esperem que PM2 t'ajudi a gestionar les teves aplicacions Node.js de manera fàcil!