Node.js was probably never intended to be run on a windows server. It runs perfectly on Linux, and you can also run it without problems as an Azure App Service.
But what if Node.js has to run on a Windows server? Currently you have 2 options, use IISNode or use NSSM.
NSSM, the Non-Sucking Service Manager allows you to run any application as a Windows Service, including the command line. And since Node.js can be started from the command line, this is my choice in this example.
WHAT YOU NEED TO KNOW BEFORE RUNNING YOUR NODE WEBSITE ON A WINDOWS MACHINE
Running Node.js as a service means that your Node.js will run locally, listening to a port. You therefore need a load balancer to route requests from the internet to the port on the Windows server. The Windows server itself have no routing capabilities. One solution is to install an IIS on the server and use a redirect module to redirect requests to the correct port, but this is not covered in this article. I am so fortunate to have a NGINX load balancer handling the routing for me.
WHAT YOU NEED TO INSTALL FIRST
Of course you need Node.js. Check the version of Node.js and NPM like this:
node -v
npm -v
You also need the latest version of NSSM.
STEP 1: CREATE A START.BAT FILE THAT CAN START NODE.JS
These start.bat files are different from site to site. This is my bat file:
cd dist
npm run start
The .bat file is a replica of what I would have typed in myself in my command line or PowerShell in order to start the website manually.
STEP 2: INSTALL A SERVICE USING NSSM
I have installed my NSSM in the C:\nssm folder on my server. And I have the website in the C:\website folder. Finally, I have a C:\logfiles folder to store logfiles. To setup NSSM, write the following:
C:\Nssm\win64\nssm.exe install Website-Service C:\website\start.bat
C:\Nssm\win64\nssm.exe set Website-Service AppDirectory C:\website\
C:\Nssm\win64\nssm.exe set Website-Service AppStdout D:\logfiles\out.txt
C:\Nssm\win64\nssm.exe set Website-Service AppStderr D:\logfiles\err.txt
The lines do the following:
- Install a service called Website-Service that runs the C:\website\start.bat file
- Set the local directory to C:\website\ (do not skip this step, or you might end up having access issues)
- Route whatever the command line outputs to the D:\logfiles\out.txt folder
- Route errors to the D:\logfiles\err.txt
Node.js is case sensitive, so do not write c:\website, use C:\website.
You will now have a service that you can start either manually or from PowerShell:
Start-Service -Name Website-Service
That’s it. You are now a Node.js DevOps expert. Happy DevOps’ing
MORE TO READ
- Download NSSM here
- How to Run NodeJS Application as a Windows Service from HelpMeGeek
- Install nodejs program as windows service by nssm by Sing’s Log
- Using nssm to automatically start a node server on windows from ankri.de
- how to run a program on start up as an administrator using NSIS and NSSM? from Stackoverflow
- NSSM Cheatsheat from Github