Maxy.fr

Automatically Start Node.js on Server Boot

If you've ever created programs using Node.js, you've probably encountered this issue: Node.js scripts don't automatically restart when you reboot your server. Therefore, you need to manually reconnect to restart them, which can be quite inconvenient.

Here's a small shell script that allows you to execute your scripts and start them every time the server starts.

The Shell Script

You'll need to create a file, which you can name as you like, and save it in the /etc/init.d/ directory on your server. In this example, my file is named "autostartnode," so make sure to modify the name in the code if you want to use a different one.

#!/bin/bash
# /etc/init.d/autostartnode

### BEGIN INIT INFO
# Provides: autostartnode
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Démarrage automatique des scripts Node.JS
# Description: Démarrage automatique des scripts Node.JS
### END INIT INFO

lancement(){
	# On créé la session 'screen' en mode détaché
	screen -dmS nomScreen
	# On se déplace dans le chemin où se trouve nos scripts .js (Node.JS)
	screen -S nomScreen -p 0 -X stuff "cd /chemin/dossier/scripts/node/$(printf \\r)"
	# On lance notre script à l'aide de la commande 'node'
	screen -S nomScreen -p 0 -X stuff "/usr/local/bin/node server.js$(printf \\r)"

	sleep 3 # On patiente 3s le temps que le script s'execute

	# On vérifie que notre session screen se soit bien lancée et on affiche le résultat
	if ! screen -list | grep -q "nomScreen"
		then
		echo "AutoStartNode : Echec lors du lancement de 'nomScreen'"
	else
		echo "AutoStartNode : Lancement de 'nomScreen' reussi"
	fi

}

arret(){
	# On supprime la session 'screen' précedemment créée
	screen -X -S nomScreen kill

	sleep 3 # On patiente 3s

	# On vérifie que l'arrêt a bien fonctionnée
	if ! screen -list | grep -q "nomScreen"
		then
		echo "AutoStartNode : Arrêt de 'nomScreen' reussi"
	else
		echo "AutoStartNode : Echec lors de l'arrêt de 'nomScreen'"
	fi

}

case "$1" in
start)
	lancement
;;
stop)
	arret
;;
restart)
	arret
	lancement
;;

*)
echo "Usage: /etc/init.d/autostartnode {start|stop|restart}"
exit 1
;;
esac

exit 0

The program uses 'screen,' which allows creating multiple terminal sessions. One session will be created for each Node.js script to be executed. The advantage of this technique is that you can easily access each terminal to check the status of your Node.js server.

The program is straightforward, consisting of two functions: one for launching and one for stopping scripts. You can use three arguments: start, stop, or restart, which determine whether your code runs when the server starts or stops.

The entire program is well-commented, so I won't explain it further. For the launch function, it creates a screen session, executes the Node.js script, and checks that the session is running.

The program is not highly optimized and covers only the essentials. It would be a good idea to check if a screen session with the same name already exists when creating one, for example.

Regarding the "BEGIN INIT INFO" section, you can research it if you'd like. It's necessary for automatic execution.

 

Configuration for Automatic Script Execution at Server Startup

Now that your script is ready, you'll need to configure your server to execute it automatically when starting or stopping the server.

The first step is to give execute rights to your new script. Use this command:

chmod +x /etc/init.d/autostartnode

Now, to instruct your server to run the script every time it starts or stops, use the following command:

sudo update-rc.d autostartnode defaults

It should be working now.

 

Once again, this technique is somewhat rudimentary and not highly optimized. If you have other techniques or suggestions, feel free to share them in the comments.

Catégories : Linux, Node.JS

Par Guillaume le 10/08/2016 à 22:33

Partager l'article :

Articles similaires

Comment résoudre le message Possible attack detected dans ISPConfig ?

Lorsque vous gérez un serveur web avec ISPConfig, il peut arriver que vous rencontriez le message d'avertissement "Possible attack detected. This action has been logged." sur l'interface web. Rendant son accès impossible. Cette alerte peut être déclenchée par...

Postfix : Régler le problème d'envoi d'email vers Gmail à cause d'IPV6

Si vous n'arrivez pas à envoyer d'email vers les adresses gmail depuis votre serveur et que vous obtenez l'erreur suivante, il s'agit probablement d'un problème de configuration si vous avez une IPV4 et une IPV6. Voici l'erreur en question : Our system has detected that this message...

Retrouver et arrêter une instance de Node.JS restée active

Si vous vous amusez un peu avec Node.JS, vous avez surement déjà exécuté un fichier node et le laisser tourner en fond. Vous avez l'habitude d'utiliser le raccourcie ctrl + c (cmd + c) ou ctrl + z (cmd + z) pour suspendre ou arrêter son processus, cependant si vous...