Distriartistas!

martes, 12 de diciembre de 2017

Añadir aplicación al inicio y como comando en linux [ Unix - Node.js ]

Añadir aplicacion al inicio de linux como service


Opción 1:

Crear a myapp.service file (remplace 'myapp' con el nombre de su app):

[Unit]
Description=My app

[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note RHEL/Fedora uses 'nobody', Debian/Ubuntu uses 'nogroup'
Group=nobody  
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp

[Install]
WantedBy=multi-user.target
 
Copy your service file into the /etc/systemd/system.

Start it with systemctl start myapp.

Enable it to run on boot with systemctl enable myapp.

See logs with journalctl -u myapp

Fuente: StackOverflow

Opción 2:

server.js:

const http = require('http');

const hostname = '0.0.0.0'; // listen on all ports
const port = 1337;

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
}).listen(port, hostname, () => {
  console.log('Server running at http://${hostname}:${port}/');
});

Guardar en la ruta  

/opt/nodeserver/server.js.

Verificar que el servidor funcione correctamente:
 
node /opt/nodeserver/server.js
 
Server running at http://0.0.0.0:1337/

Systemd

Create the service file

Crear  /etc/systemd/system/nodeserver.service

[Unit]
Description=Node.js Example Server
#Requires=After=mysql.service       # Requires the mysql service to run first

[Service]
ExecStart=/usr/local/bin/node /opt/nodeserver/server.js
# Required on some systems
#WorkingDirectory=/opt/nodeserver
Restart=always
 # Restart service after 10 seconds if node service crashes
 RestartSec=10
 # Output to syslog
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-example
#User=
#Group=
Environment=NODE_ENV=production PORT=1337

[Install]
WantedBy=multi-user.target

Enable the service

Ejecutar:
 
systemctl enable nodeserver.service
 
Mostrará esto al ejecutarse correctamente: 
 
Created symlink from /etc/systemd/system/multi-user.target.wants/nodeserver.service to /etc/systemd/system/nodeserver.service.

Start the service

systemctl start nodeserver.service

Verificar que se esté ejecutando correctamente:

Ejecutar:
 
systemctl status nodeserver.service

Mostrará esto al ejecutarse correctamente:
 
 ● nodeserver.service - Node.js Example Server
   Loaded: loaded (/etc/systemd/system/nodeserver.service; enabled)
   Active: active (running) since Thu 2015-12-31 09:29:35 NZDT; 7s ago
 Main PID: 8952 (node)
   CGroup: /system.slice/nodeserver.service
           └─8952 /usr/local/bin/node /opt/nodeserver/server.js

Dec 31 09:29:35 fileserver nodejs-example[8952]: Server running at http://0.0.0.0:1337/
 
*Nota: podría generar un error por la ubicación del /usr/local/bin/node, ejecutando
which node les mostrará la ruta correcta.  

Security / testing

Ruta del servicio: 

/etc/systemd/system/nodeserver.service

Cuando se realicen cambios en el archivo .service es necesario ejecutar:

systemctl daemon-reload
 
Después de reiniciar systemctl se debe reiniciar nuestro servicio:

systemctl restart nodeserver.service
 
Como sugerencia es bueno revisar el estado de nuestro servicio:

systemctl status nodeserver.service

Podemos terminar el proceso manualmente con el ID del proceso y reiniciar mediante systemctl:

ps -ef | grep server.js     # find the current pid
kill 12345                  # kill the process by its pid reported above
ps -ef | grep server.js     # notice node process is immediately respawned with a different pid

Fuente: Axllent

* Nota: El servicio puede ser administrado mediando systemctl o service

Añadir aplicación como system command

  1. Crear un directorio llamado "bin" en su ruta home.
  2. Actualizar la variable de entorno $PATH añadiento la ruta a la carpeta bin en el archivo .profile o .bash_profle
    Ejecutar:

    export PATH=$PATH":$HOME/bin"
     
  3. Crear un script llamado "hello" en el directorio bin y darle permisos de ejecución al mismo

    $ chmod +x hello.

    #!/bin/bash    
    echo My first program
     
  4. Recargar el registro .profile or .bash_profle:

    $ . ~/.bash_profile o $ . ~/.bashrc
     
  5. Desde cualquier ruta en la terminal podrá ejecutar

    $ hello
     
    Si todo funciona bien mostrará:
     
    My first program
    
    
    Adcional hice este ejemplo ejecutando una aplicación node
     
    1. Tener enrutado al $PATH la carpeta bin
    2. crear un archivo llamado world
     
       #!/usr/bin/node 
       console.log("Hello World!"); 
     
    3. Desde cualquier ruta ejecutar 
     
       $ world 
       
       Mostrará: 
       
       Hello World!   
     
Fuente: Stackexchange

Ver logs en tiempo real

Ejecutar:
$ journalctl -u kospr.service -f

Para crear un comando para ver sus registro en tiempo real en la carpeta bin crean un archivo llamado serverLogs:

#!/bin/bash
journalctl -u nodeserver.service -f

y en la terminal ejecutan 
$ serverLogs




No hay comentarios:

Publicar un comentario