Run a Node JS app in VPS
In this article, I will be discussing how we can run a Node Js app inside a VPS so that we can access it from anywhere.
I have a basic VPS with Ubuntu and a subdomain setup where I will be setting up my node application. If you don't know how to set up a subdomain, you can check my previous article. First of all login into your VPS by using putty or Powershell by using the command ssh username@host .
Step 1- Installing Node
Install Node JS and NPM by using the command:
You can always verify the installation by checking their version numbers:
Step 2- Setting up PM2
Now our Node js is installed, now all you have to do is to take any sample code that you want to run and navigate to that folder. My Node app is configured to run at port 2121. Run the app to check if it is running.
Install the PM2 package using the command:
Now we will run our Node App using the PM2 command, make sure you are inside your Node project Folder:
After this, you could see something like this:
Now that our app is running by PM2, we will make sure that the app runs even after a server restart, we can do so by:
The above command’s output will generate another command to be run, it will look something like this:
Just run that command by copying and pasting in your own terminal.
Save the process by using the command:
Now take a break and restart your VPS.
After your machine has successfully restarted, ssh into it and start the service with systemctl:
Dont forget to use your username instead of farhazalam .
Now, you can check the status by typing:
Stop, start, restart, or check your pm2 instance by running:
Step 3- Set up Nginx Server Block
Open the server block in which you want to configure your node app, I will be using my subdomain for this. You can also use the default server block to set up. Open the server block by typing:
Search for the location block inside the server block and paste the following lines.
Note: Don’t forget to change the localhost port to the port which you have set for your node js app.
Note: Comment the line try_files $uri $uri/ =404; by adding a # before it.
The final block will look something like this:
Optional
You can also add another location block if you want to run some other node js with different ports but on the same domain. you can do it by adding like this:
You can access the second location by www.domain.com/api2 .
Now all that is left is to check for syntax errors and then restart your Nginx server:
Voila, you have now your node js app running in your server which can be accessed from anywhere.
Свой Node.js хостинг на VPS
По ходу изучения Node.js я создал много маленьких проектов. В дальнейшем мне понадобилось развернуть некоторые из них на сервере, чтобы иметь возможность развивать их в дальнейшем. Существующие хостинги Appfog и Heroku имеют ряд серьезных ограничений на бесплатных аккаунтах. На Appfog’е можно запускать одновременно не больше 2-х приложений, и бесплатная регистрация у них уже отключена. На Heroku можно создать только 5 приложений (без базы данных) без подтверждения аккаунта привязкой банковской карты. Платные аккаунты стоят очень дорого для меня (я ведь не зарабатываю на этих маленьких проектах): $20 долларов на Appfog, а heroku еще дороже. Коллеги порекомендовали попробовать хостинг на Digital Ocean — виртуальный сервер за $5 доларов в месяц, на котором можно легко настроить собственный хостинг node.js-проектов.
О том, как организовать такой хостинг, и будет идти речь в этой статье. Если по ходу руководства у вас возникнут проблемы, поищите их решение в конце статьи.
Создаем VPS
1. Регистрация на DigitalOcean
Первым делом регистрируемся на сайте DigitalOcean. Здесь мы купим VPS — виртуальный сервер. После удачной регистрации и входа в свою админку жмем на большую зеленую кнопку «Create» и нам предложат активировать свой аккаунт, внеся $5 долларов. Ниже на странице есть место для указания счастливого купона на $10, вводите OMGSSD10 или поищите свежий купон. Так как моя банковская карточка не подошла хостеру, я оплатил пейпалом и у меня на счету оказалось $15. Этого должно хватить на 3 месяца.
2. Создаем SSH-ключ
Доступ к удаленным серверам обычно делается по ssh. Это такая технология защищенных соединений. Зайти в нашу будущую VPS можно по паролю или по SSH-ключу. Я настоятельно рекомендую второй вариант, не придется все время вводить пароль. Также, SSH-ключ все равно нужно будет указать при создании нашего нового «дроплета» (словом «droplet» DigitalOcean называет виртуальный сервер).
Выполните следующие две команды в терминале, чтобы сгенерировать ssh-ключ:
И тут нас просят ввести имя файла ключа. Рекомендую использовать что-нибудь вроде id_rsa_digitalocean_dropletname , где имя дроплета — это либо имя домена, на который мы привяжем наш сервер, либо просто какое-нибудь осмысленное название. Парафразу можно оставить пустой, и так сойдет.
После этого будет создано два файла: ssh-ключ и public-ключ. Скопируем публичный ключ в буфер обмена модным способом:
Теперь зайдем в админку в digitaloceans в раздел SSH-keys и создадим там новый ключ, вставив его из буфера обмена.
3. Создаем дроплет
- В качестве hostname укажите доменное имя или что-нибудь осмысленное, это название роли не играет
- Размер выбирайте самый маленький, его потом можно будет увеличить из терминала
- Регион любой, я выбрал Амстердам
- Образ выберите на вкладке Applications, c названием «Dokku v0.2.3 on Ubuntu. » или похожим
- Укажите SSH-ключ, который мы создали на предыдущем шаге
Выбранный образ помимо операционной системы Ubuntu 14.04 содержит самое главное: Dokku. Это готовая система для хостинга node.js-проектов, очень похожая на Heroku. Использование образа с предустановленным Dokku избавит нас от необходимости устанавливать и настраивать систему для хостинга Node.js.
4. Настройка Дроплета и DNS
Теперь нужно настроить новосозданный сервер. Зайдите в браузере по IP-адресу дроплета и вы увидете экран настройки. Если такой страницы нет, смотрите что делать в конце статьи.
Здесь вы должны убедится, что поле «Public Key» заполнено. Если нет — укажите свой public key из недавно сгенерированного ключа. Однако практика показала, что лучше вообще удалить такой дроплет и создать новый, правильно указав SSH-ключ.
Если у вас нет доменного имени, то оставьте все, как есть, жмите «Finish setup» и переходите к следующему пункту. Ваше приложение будет доступно примерно так: «19.19.197.19:46667», по IP адресу и номеру порта. Если вас это не устраивает — срочно купите доменное имя. В любом случае, настроить доменное имя можно будет позже, о чем я расскажу в конце.
Если вы укажете доменное имя, у вас будет возможность настроить доступ к приложениям через поддомены. Например, если ваше доменное имя mydomain.com , тогда ваше приложение будет доступно по адресу app.mydomain.com . Также есть возможность привязать приложение на главный домен, но об это я в данной статье не расскажу.
Укажите в поле Hostname ваше доменное имя и поставьте галочку «Use virtualhost naming for apps». Теперь идите в панель управления вашим доменным именем и впишите две новые настройки примерно так:
Точный синтаксис уточните у себя в админке доменного имени или у домен-провайдера.
Теперь возвращайтесь на страницу настройки дроплета и жмите «Finish setup».
5. Настраиваем использование SSH
Давайте попробуем соединиться с нашим новым сервером. Чтобы получить доступ дроплету через SSH-ключ, нужно еще одно маленькое действие. Откройте терминал и передите в папку с ssh-ключами:
Если у вас еще нет файла «config» в этой папке (проверка — $ ls ), то его необходимо создать:
Теперь открываем config( $ open config ) и записываем в него следующие данные:
Где в первой строчке IP адрес или доменное имя, на второй строчке — имя созданного ssh-ключа для этого дроплета.
Где после «@» надо указать или доменное имя, или IP.
Если вы пропустили создание SSH-ключа, войти можно по паролю, который пришел к вам на почту. Для этого выполните ту же команду:
и на вопрос о продолжении соединения напишите «yes». После этого введите пароль.
Если вы увидели приветственный экран, значит все хорошо. Закроем соединение командой exit и перейдем к следующему пункту.
Деплоим приложение
Сервер готов, теперь пришла очередь развернуть тестовое приложение и проверить его работу.
1. Подготавливаем проект
Возьмите простой проект, типа Hello, world, без mongodb и прочего. Проверьте, что в проекте есть самое главное: «package.json», «Procfile» и какой-нибудь «app.js». «Package.json» должен выглядеть примерно так:
Содержание файла package.json важно, так как по нему dokku будет устанавливать модули для приложения. А Procfile должен выглядеть так:
Инициализируем в папке проекта репозиторий (если его не было), добавляем все файлы и коммитим:
Теперь наш проект готов к разворачиванию на сервере.
2. Заливаем и запускаем проект
Деплоить приложение будем с помощью команды git push . И для этого добавим ссылку на удаленный репозиторий нашего дроплета:
Если у нас было доменное имя для дроплета, то пишем его после «dokku@», иначе — указываем IP. После двоеточия мы указываем имя приложения. Этот индификатор будет использоваться внутри dokku.
Теперь вызываем команду push :
И начинается загрузка приложения, установка модулей. В конце на экране покажется url, по которому можно запустить проект. Это будет ссылка вида 192.88.67.168:46567 или app1.mydomain.com, в зависимости от настроек dokku.
По идее проект должен быть запущен после этого. Но если нет, то заходим в по ssh в наш дроплет и выполняем две команды
Запускаем в браузере ссылку, полученную ранее, и радуемся!
Проблемы и их устранение
Я сам разбирался с настройкой такого хостинга более суток, и набил несколько шишек. И чтобы вы могли съэкономить свое время, привожу здесь несколько возможных проблем и пути их решения.
1. Мою банковскую карточку не приняли для оплаты
Они такие, да. Даже Visa Classic им не нравится. Оплатите через PayPal, это не трудно.
2. Создал дроплет, но по IP адресу нет страницы настройки dokku
- указать образ с Dokku
- нажмите кнопку «Rebuild from Image».
3. Не могу получить доступ к дроплету ни по паролю, ни по SSH
- Наверное, вы как-то пропустили шаг настройки dokku, или dokky создался не правильно.
- Проверьте, если доступна страница настройки dokku по IP адресу дроплета, то вернитесь к шагу 4 создания VPS.
- Если страницы настроек нет, тогда попробуйте сбросить пароль и повторить попытку доступа через терминал. Если даже в этом случае доступ по паролю будет неудачным, тогда переустановите дроплет, как описано в предыдущем пункте.
4. Я не знаю пароля от дроплета
Если у вас нет пароля, зайдите на страницу управления дроплетом, вкладка «Access» и сделайте reset пароля. Тогда на почту придет новый пароль.
5. Проект не запускается по указанной ссылке
Если настройки dokku верны, такая ситуация возможна, если приложение запустилось с ошибкой и было закрыто. Зайтиде по ssh в дроплет и проверьте логи:
Возможно, ошибка будет понятна. Или же вы забыли запустить ваш проект после push’а:
6. Я пропустил создание SSH, и теперь хочу сделать авторизацию по SSH-ключу
Я пытался создать новый дроплет без указания ssh-ключа на странице создания дроплета, но на странице настроек dokku все равно просят ввести паблик-ключ. После этого я принял некоторые действия, но все равно зайти по ssh-ключу у меня не вышло, только пароль. Так что я не знаю, как лучше действовать в данной ситуации. Возможно, ошибка происходила при команде копирования ssh ключа в дроплет. Гуглите. В крайнем случае создайте новый дроплет с самого начала, по уму, как в этом руководстве. Пример поиска.
7. Как добавить доменное имя к уже существующему дроплету
В дроплете зайти в папку dokku и открыть для редактирования HOSTNAME:
Нажать клавишу «i» и записать в файле «HOSTNAME» доменное имя вместо IP адреса; затем нажать Esc , кнопки :wq и Enter . Ура! Мы только что успешно использовали легендарный Vim!
Чтобы проекты запускались на поддоменах, нужно создать файл VHOST :
И записать в файле доменное имя таким же способом, как это было в предыдущем пункте. В противном случае проекты будут доступны через порт. Теперь надо перезалить проект, а перед этим удалить его из dokku:
Установка и настройка Node.js на VPS

2. Ставим Node.js:

3. Проверяем установку командами:

4. Устанавливаем инструментарий разработчика.

5. Создаем тестовый файл:
Добавляем в наш файл следующее содержимое:
Порт может быть любым свободным, IP_ADDRESS — IP-адрес Вашей VPS.

6. Запускаем:
Должна появиться строка Server running at http://IP_ADDRESS:8080/

7. Проверяем доступ, подключившись с другого терминала командой:

И открываем в браузере ссылку http://IP_ADDRESS:8080/

Если ссылка в браузере не открывается/соединение через curl не устанавливается, проверьте настройки firewall на Вашей VPS.
Рейтинг лучших SSD VPS по ссылке.
Installing Node.js on a VPS Server

Node.js is an open-source platform that helps JavaScript users execute their code outside a web browser. It is a free solution that runs well on almost any operating system. In terms of hosting, VPS servers provide a perfect environment to integrate Node.js apps with developer tools and APIs.
Let’s see what you need to do to use Node.js on both managed and self-managed VPS servers.
Table of contents:
- What is Node.js
- Why Node.js
- What is Node.js Used For?
- Node.js System Requirements
- Installing Node.js and npm
- Starting Node.js Apps
- How to Stop an Application
- Connect your Web Server with a Running Node.js App
- Deploying a Node.js Application with SPanel
- Conclusion
- Frequently Asked Questions
What is Node.js?
Node.js is a cross-platform, event-driven JavaScript runtime environment. It is built on Chrome’s V8 JavaScript engine alongside other development frameworks like MongoDB, Express.js, and AngularJS. Node.js lets you use JavaScript to create web servers, networking tools, and modules responsible for a number of core functions.
Because Node.js works with JavaScript only, it’s more accessible to a broad community of developers. At the same time, the APIs its modules use simplify the process of writing server applications.
Although you can run your NodeJS apps without it, experts recommend installing npm – Node.js’s official package manager. It consists of a client and an online database (the npm registry) of over 1 million free and paid-for packages. Thanks to npm, developers from all over the world can tap into an enormous pool of ready-made resources that help them speed up the development process.
Why Node.js?
Node.js brings many advantages to the table. For one, it’s already a lightning-fast scripting environment, and since it is built on Google’s engine, its performance is likely to improve over time. The npm registry is also expanding, so developers will probably have an even easier time finding what they’re looking for in the future.
Speed is far from the only thing Node.js is famous for, though. Read about it on the internet, and you’ll see that most people talk extensively about its asynchronous, event-driven architecture.
Let’s take a closer look at it and see how developers can benefit from it.
To understand how it works, we need to compare it to one of the alternatives. PHP is used by almost 80% of the world’s websites, so we’ll use it as an example. If a PHP application is asked to open a file, it won’t handle any other requests before it opens the said file. All subsequent requests depend on the execution of the first one.
By contrast, Node.js’s architecture is asynchronous, meaning multiple requests can be processed simultaneously. One request doesn’t need to wait for the execution of another, and the content delivery is much more efficient. As a result, the applications created with Node.js are fast, robust, and easily scalable.
In light of all this, it’s little wonder that tech giants like IBM, LinkedIn, Netflix, and PayPal have used Node.js during the development of some of their products.
What is Node.js Used For?
Node.js has been around since 2009, which isn’t that long compared to other web technologies. Nevertheless, it has already proven its worth as a robust development framework with dozens of uses in a number of different spheres.
Here’s where it shines the most:
Chat applications
The ability to efficiently deliver dynamic content, coupled with the existence of JavaScript libraries for real-time web applications, make Node.js perfect for developing excellent instant messaging services.
Browser games
HTML5 and the evolution of other technologies mean that you can now create great browser-based games without relying on horrible Flash animations. Node.js is one of the best new alternatives.
Streaming applications
Once again, Node.js’s asynchronous I/O enables streaming services to provide real-time, high-quality video to hundreds of thousands of users at once.
Back end tools
JavaScript is mainly associated with front-end development, but the truth is, there are JS libraries that enable developers to create fast and reliable command-line apps with Node.js.
Node.js System Requirements
Node.js’s lightweight design is one of the things that has made it so popular with developers. You have to bear in mind that you’ll need reasonably powerful hardware if you want to use Node.js on Windows. However, when it comes to Linux, the resource usage is so low, you can run standard Node.js applications even on a Raspberry Pi.
There are Linux versions for ARM and 64-bit architectures, and on Windows, it runs on both 32- and 64-bit machines. macOS servers need 64-bit chips to run Node.js, and there’s also an official image for Docker containers.
All in all, Node.js can run on most modern setups.
Installing Node.js and npm
Because it’s available on so many different operating systems and setups, there’s no one-size-fits-all tutorial that will show you the exact steps for installing Node.js. Most web hosting VPS servers run on Linux, so we’ll focus on it. Even with it, however, the installation process varies from distribution to distribution. Here are the two most common scenarios.
Installing Node.js and npm from the Ubuntu Official Repository
Node.js is popular enough to make its way into the official software repositories of one of the world’s most popular Linux distributions – Ubuntu. If your VPS uses Ubuntu, installing Node.js involves a few simple steps. Let’s have a look at them.
1. Update Your VPS
Before installing Node.js, it is advisable to update the package index for your Ubuntu virtual server. You can do so with the following command:
sudo apt-get update
2. Install Node.js
Because Node.js is a part of Ubuntu’s official repository, you can install it with a single command:
sudo apt-get install nodejs
NOTE: If you take this approach, Ubuntu will install the latest available package from the repository. This installation method isn’t suitable if you need a specific version of Node.js.
3. Install npm
Once again, you can install npm’s latest version with a single command:
sudo apt-get install npm
4. Verify that the installation is a success
The easiest way to ensure that the installation is successful is to ask Ubuntu which versions of Node.js and npm you’re currently using.
For Node.js, the command is:
and for npm, you need to enter:
Installing Node.js Manually
If you don’t run Ubuntu or prefer to install a version of Node.js other than the latest one, you can perform the installation manually. It’s a bit more complicated than setting it up straight from the repository, but as long as you’re careful, you should have no problems doing it. Here are the steps:
1. Download and extract the Node.js archive
You first need to make sure you’re in your home directory. The command to go straight there is:
Next, you can use the following command to download the Node.js archive:
NOTE: With this command, you will download version 14.18.1 (the latest at the time of writing). If you want to download a different version of Node.js, you’ll need to adjust the URL accordingly.
2. Extract the archive
To extract the Node.js archive you’ve just downloaded, use the following command:
tar xvf node-v14.18.1-linux-x64.tar.xz
The files will be extracted in a new directory called node-v14.18.1-linux-x64.
3. Rename Node.js’s directory to make your life easier
While not strictly necessary, this step will simplify the installation process. What we’ll do is rename the folder with the extracted files from node-v14.18.1-linux-x64 into something less cumbersome like node, for example. Here’s the command:
mv node-v14.18.1-linux-x64 node
4. Install Node.js’s and npm’s binaries
The final three commands will create the required directory, copy the binaries in it, and create the necessary symbolic links:
/bin
cp node/bin/node
bin
ln -s ../node/lib/node_modules/npm/bin/npm-cli.js npm
5. Check whether the installation is successful
Once again, you can ask Linux which versions of Node.js and npm are installed on the server to confirm that everything is fine. The commands are:
In our case, the responses should be v14.18.1 and 6.14.15, respectively.
Starting Node.js Apps
Having installed Node.js and npm on your server, you’re probably wondering how to start an application with them. How you’re going to go about it depends on the app itself.
Using npm
If you need to start a production-ready app with a valid package.json file, you can use the npm package manager. The command is:
nohup npm start –production &
Using Node
If your app doesn’t have a package.json file, you’ll need to use Node.js itself. You can do it with the following command.
nohup node [your app’s name].js &
Note that if you choose to run an app that does not have an included package.json file, you won’t be able to manage it with npm.
How to Stop an Application
To terminate a running application, we need to kill the process. Luckily, there is an easy command to stop any Node.js processes on the server:
Connect your Web Server with a Running Node.js App
Because of the various combinations of technologies а VPS can handle, there are many ways to connect your website to a Node.js app. Since Apache is one of the most common web servers, we will use this as the showcase platform.
We want to utilize the .htaccess file to perform the connection between the website and the Node.js app.
The .htaccess file is located in the document root folder (home/[your username]/public_html/). If you have a web hosting control panel installed on your server, you can get to it via the integrated file manager. Otherwise, your option is to access the server through SSH and open it with a text editor.
Here’s what you need to add to your .htaccess file:
DirectoryIndex disabled
RewriteEngine On
RewriteRule ^$ http://127.0.0.1:XXX/ [P,L]
RewriteCond %
RewriteRule ^(.*)$ http://127.0.0.1:XXX/$1 [P,L]
Replace “XXX” with the port number of your Node.js application. Once done, remember to save the changes to your .htaccess file before exiting the editor.
Deploying a Node.js Application with SPanel
Those of you finding all these steps a bit intimidating will be happy to learn that if you have an SPanel VPS, you don’t need to go through any of them.
Node.js integration used to be one of the most heavily requested features by our SPanel clients, and we had no other choice but to implement it. SPanel servers have always supported Node.js, but right now, you don’t need to install it yourself or ask someone else to do it.
Node.js is set up and configured on all SPanel servers, and inside our proprietary management platform, you’ll find an easy-to-use tool that helps you launch applications in a matter of clicks. Here are all the steps:
1. Upload your application to a folder of your choice.
You can use your favorite FTP client or SPanel’s File Manager to upload the Node.js app from your local computer to the virtual server.
2. Deploy the application through SPanel’s NodeJS Manager.
SPanel’s NodeJS manager is available in the User Interface.
The Deploy a New App button opens a popup that lets you quickly launch your application. All you need to do is set the application URL, the port it will listen to, and the path to the app itself.
NOTE: You can only use ports between 3000 and 3500 for your Node.js applications.
Click Deploy to complete the process.
3. Manage your Node.js applications.
SPanel’s NodeJS Manager displays a list of all currently deployed Node.js applications. The Actions drop-down menus let you Stop, Restart, and Undeploy them one by one.
Conclusion
If you want to start a simple blog or a small online store, you probably don’t need Node.js. The JavaScript runtime environment is more suitable for more complex projects, usually led by people with more experience in the field.
With the correct commands, they should have no problems installing and using Node.js on a self-managed virtual server. However, even the biggest command-line wizards will appreciate the convenience of launching applications from an easy-to-use graphical user interface like SPanel’s NodeJS Manager.
Frequently Asked Questions
Must I pay to use Node.js?
Node.js is open-source and is free for use. Having said this, if you develop your Node.js project within a proprietary integrated development environment (IDE), there will likely be a fee involved as it is a commercial product.
What is NPM?
NPM is short for Node Package Manager. It serves as a repository for JavaScript packages that developers incorporate into their projects. It also gives web devs the capability to manage a specific version of each package.