How to Install node.js app on VPS shared hosting?
In this article, I will show you how to install node.js on shared hosting
if you just purchased new shared hosting and there is not node.js installed.
Don’t worry in this step-by-step guide you will learn to install node.js with SSH without sudo or root access.
I am a Windows user, for connecting to the server via SSH i will use putty software that’s free and easy to use.
I assume that you have already installed putty if not just google you will see lots of tutorials on How to install putty on windows.
How to use putty?
search putty in your window’s search bar and click on putty to execute.
You will see the following screen
Enter the following values in putty for connecting to the server
1.Enter Your Server/cPanel IP Address in * hostname (or IP address field*
Размещение нескольких приложений Node.js на одном VPS (при помощи Nginx, Forever и Crontab)
Чтобы следовать данному руководству, необходимо предварительно установить Nginx и Node.js. чтобы получить инструкции по установке данного ПО, читайте статьи:
Кроме того, вместо http://[ip-адрес-vps]:[порт] лучше использовать домен, подключив к нему запущенный сервис Node.js.
Запуск приложения Node.js с помощью Forever
Forever – это простой командный инструмент, который гарантирует, что скрипт/приложение будет работать «вечно». То есть если в результате ошибки происходит сбой приложения, forever найдет способ исправить ее и перезапустит приложение.
Установите инструмент forever глобально, это займет считанные секунды:
npm install forever -g
Чтобы запустить скрипт с помощью forever, выполните следующие действия:
- перейдите к приложению Node.js:
- и запустите файл main.js через forever:
forever start —spinSleepTime 10000 main.js
где –spinSleepTime 10000 обозначает минимальный аптайм (в миллисекундах) между запусками аварийного скрипта. Эта команда сработает практически во всех случаях.
Теперь направьте браузер на http://[ip-адрес-vps]:[порт], чтобы увидеть приложение в действии.
Подключение домена к приложению Node.js
Теперь нужно добавить запись DNS в панель управления, чтобы подключить доменное имя к виртуальному выделенному серверу.
Итак, выполните следующие действия:
- Войдите на сервер;
- В панели найдите раздел DNS;
- Добавьте домен, нажав кнопку ‘Add Domain, укажите нужный VPS и доменное имя;
- Скопируйте полученный Nameserver и внесите его в запись DNS в панели управления.
Примечание: эти изменения не вступят в силу моментально, поскольку обработка может занять до 24 часов.
Подключение домена к сервису Nginx
В данном разделе речь пойдет о подключении обратного прокси-серера с помощью Nginx.
Для начала нужно при помощи наиболее удобного текстового редактора создать файл для домена в /etc/nginx/conf.d/. По соображениям совместимости файл должен быть назван доменным именем.
Примечание: файл можно назвать как угодно, важной часть имени файла является расширение .conf.
Теперь нужно скопировать следующий фрагмент кода и вставить его в только что созданный файл:
server <
listen 80;
server_name your-domain.com;
location / <
proxy_pass http://localhost:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection ‘upgrade’;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
>
>
Просто замените your-domain.com своим доменным именем, а YOUR_PORT – номером порта, который прослушивает приложение Node.js.
Примечание: чтобы иметь возможность ссылаться на несколько доменов одного приложения Node.js (например, www.example.com и example.com) необходимо добавить следующий код в раздел http файла /etc/nginx/nginx.conf:
Когда изменения DNS вступят в силу, направьте веб-браузер на доменное имя; это должно открыть работающее в сети приложение.
Запуск приложения Node.js при перезагрузке
Инструмент forever очень полезен при аварийных сбоях приложения; но что делать при перезагрузке сервера?
В таком случае нужно использовать простую таблицу crontab, которая может предотвратить неожиданные простои приложения.
Создайте файл по имени starter.sh в домашнем каталоге приложения и скопируйте в него следующий код:
#!/bin/sh
if [ $(ps -e -o uid,cmd | grep $UID | grep node | grep -v grep | wc -l | tr -s «\n») -eq 0 ] then
export PATH=/usr/local/bin:$PATH
forever start —sourceDir /path/to/your/node/app main.js >> /path/to/log.txt 2>&1
fi
где main.js нужно заменить именем главного скрипта приложения.
Чтобы этот скрипт запускался при каждой перезагрузке сервера, нужно отредактировать crontab:
How To Setup a Node.js Development Environment on a VPS for a Team

In this tutorial, we will setup a Node.js development environment, which allows you to include rapidly new team members into the development process of your Node.js applications. This method can also be applied if a developer wants to create several versions of an application simultaneously.
This method is based on Node.js interacting with Nginx over Unix sockets instead of ports. Let’s assume that you have your development versions of the application at login.dev.nodeapp.com . In addition, we will hold the sockets for every developer in the /tmp directory, like /tmp/login.dev.nodeapp.com.sock .
Requirements
You will need to have Nginx and Node.js installed. Additionally, we will assume that you already have a domain (for example nodeapp.com ) linked to your VPS. Note: you should also setup wildcard CNAME record for your domain. There are already well written tutorials about these topics on DigitalOcean:
Setting Up Nginx
We should create a new Nginx configuration file /etc/nginx/sites-available/dev.nodeapp.com which contains:
Link this configuration to sites-enabled folder and restart Nginx:
Now Nginx is ready to accept user requests and guide them to the developer’s app copy, depending on URL. For example:
Modifying Node.js App
We will use a minimal webserver example from the Node.js, but the same modifications can be applicable for any Node.js server (like express).
The thing is, we need to change the default port-listening behavior into socket-listening:
Now you can run your application node app.js and access it on http://yourlogin.dev.nodeapp.com .
Note: when Node.js starts listening for sockets, it creates a specified file. But if the socket file already exists, Node.js will fail to start listening. So we should make sure we remove the socket from the previous run.
The other thing is, we should create a socket with full access for all, so Nginx will be able to use it. It’s fine for development, but might not be good for production.
And that’s it, congratulations! All you need now to introduce a new developer to create user on your VPS.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Due to a network error, some resources are not loading
If you can see two identical Namecheap logos below, please refresh the page and try again.
If that doesn’t solve the problem, please follow these steps:
If you need any additional assistance, open Help Center and contact support via live chat or open Support page and submit a ticket.
| Subtotal | $0.00 |
View Cart
We stand with our friends and colleagues in Ukraine. To support Ukraine in their time of need visit this page.
How to install Node.js on a VPS or a Dedicated server
First of all, it is required to access the server in question via SSH as a root user.
In case you are using a Unix-based OS (Linux or macOS), you can easily run the Terminal
Application (a command line emulation program and connect to the server) using the command:
ssh root@serverip -pPORT

This command has the following values:
Serverip — the IP address of your VPS or Dedicated server
PORT — 22.
If you’re using Windows OS, you can do this through an SSH client. You can find a list of free SSH clients here.
In the next example, we used the PuTTY SSH client to install Node.js:
1. Open PuTTY to launch the configuration screen. Here, you should fill out the following fields:
Host Name: the IP of the server;
Port: your server’s port (22 by default);
Connection type: SSH.
It should look something like this:

2. The PuTTY Security Alert screen prompt (pictured below) appears the first time you connect. Click Yes:

You are now looking at the SSH prompt login screen:

3. When prompted with login as:
Enter your username — root and press Enter.
After that, enter your root password and press Enter.
PLEASE NOTE: your password won’t be visible upon entry. It is an intentional security feature.
Completing these three steps logs you into your SSH server. From here, you can install Node.js.
4. To download Node.js version 10 LTS archive in your root home directory, type in the following command:
We’ve used this version as an example. If you need a different version, you can select an alternative from the official versions here.
5. It’s now time to unpack the downloaded archive. Use the command:
6. Replace node-v10.16.3-linux-x64.tar.xz with the name of the archive you have downloaded in
your case.
Executing this command launches a long prompt with the names of the files that are getting extracted.
No worries; this is absolutely normal. It means that the unpacking process was successful.
7. Rename the extracted folder to nodeext with the following command:
9. Node.js and NPM should now appear on the server. You can double-check they installed with the following commands:
This guide describes the installation of Node.js and NPM on the server.
Naturally, you would like to use them with an actual application. There are different possible configurations for Node.js apps; as such, there are multiple ways to run them.
To run a Node.js application that is production-ready and has a package.json file included, you can use the following command:
In the case you are running a Node.js app that does not have a package.json file included, you can use the following prompt:
In this case, you won’t be able to manage this application with npm.
To stop a running Node.js application, you can execute the following command via SSH:
This command kills any Node processes on the server.
Apache is standard for cPanel installations. If you run Apache, you can use a specific
.htaccess file code to make your site work with the Node.js app. Follow these steps:
1. Open up your cPanel and go to File Manager >> public_html folder.

NOTE: public_html is the folder of your site if the domain you are using is the primary domain of the given cPanel account. In case your domain is an addon domain, please check the cPanel >> Domains menu to see what folder it uses.
2. Click on the Settings button on the upper-right and make sure that the Show Hidden Files (dotfiles) option is checked. Click Save after that.


In case the .htaccess file does not exist yet, create it using the + File option on the upper-left and create the file.