Настройка vps ноде js что это
Перейти к содержимому

Настройка vps ноде js что это

Запуск NodeJS приложения на VPS на примере Telegram бота

Запуск NodeJS приложения на VPS на примере Telegram бота

В данном уроке вы узнаете, как запустить любое nodejs приложение на удаленном vps хостинге на примере telegram бота. В данном уроке мы создадим простого telegram бота, который будет приветствовать пользователя по имени и определять, с какой операционной системы он был запущен. Далее мы соединим наш проект с системой контроля версий git. После этого вы увидите шаги, которые необходимо выполнить, для запуска проекта на удаленном сервере.

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Как установить Node.js и NGINX на Debian

Описание установки node.js и веб-сервера NGINX на виртуальный сервер с операционной системой Debian.

Что такое Node.js и NGINX?

Node.js — это платформа JavaScript, которая может обслуживать динамический и адаптивный контент. JavaScript обычно является встроенным языком браузера, таким как HTML или CSS. А Node.js является серверной платформой JavaScript, сравнимой с PHP. Node.js часто работает с другими популярными серверными приложениями, такими как NGINX или Apache. В этом руководстве будет рассмотрена настройка NGINX для обработки внешних запросов, а Node.js — для обработки внутренних запросов.

Первоначальные требования

Многие из команд в этом руководстве требуют привилегий суперпользователя. Если при использовании команды sudo появляется ошибка bash: sudo: command not found, вам необходимо активировать режим суперпользователя, установить команду sudo и добавить своего пользователя в группу sudo:

su —
apt-get install sudo -y
usermod -aG sudo yourusername

Обновите локальные репозитории и пакеты:

sudo apt-get update && sudo apt-get upgrade

Установка и настройка NGINX

Установите NGINX, а также модуль screen, который будет использоваться позже:

apt-get install nginx screen

service nginx start

С помощью команды cd перейдите в следующий каталог:

Создайте новый файл, заменив example.com вашим доменным именем или IP-адресом:

Вставьте следующие строки в созданный файл, заменив example.com вашим доменным именем или IP-адресом:

#Names a server and declares the listening port
server <
listen 80;
server_name example.com www.example.com;

#Configures the publicly served root directory
#Configures the index file to be served
root /var/www/example.com;
index index.html index.htm;

#These lines create a bypass for certain pathnames
#www.example.com/test.js is now routed to port 3000
#instead of port 80
location /test.js <
proxy_pass http://example.com:3000;
proxy_set_header Host $host;
>
>

Сохраните изменения и перейдите в каталог:
cd /etc/nginx/sites-enabled/

Создайте символьную ссылку на созданный файл:
ln -s /etc/nginx/sites-available/example.com

Удалите символьную ссылку по умолчанию:
rm default

Перезапустите NGINX, чтобы применить новую конфигурацию:
service nginx reload

Создание каталогов и HTML-файлов

Создайте следующую иерархию каталогов, заменив example.com:
mkdir -p /var/www/example.com

Перейдите в созданный каталог:
cd /var/www/example.com

Создайте индексный файл:
touch index.html

Вставьте следующие строки:
<!DOCTYPE html>
<html>
<body>

<center>
<p>
<b>
If you have not finished the guide, the button below will not work.
</b>
</p>
</center>

<center>
<p>
The button links to test.js. The test.js request is passed through NGINX and then handled by the Node.js server.
</p>
</center>

Установка Node.js

На этом этапе NGINX прослушивает порт 80 и обслуживает контент. Он также настроен на передачу запросов приложения /test.js на порт 3000.

Установите Node Version Manager:
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Закройте и снова откройте свой терминал.

Установите Node.js с помощью следующей команды:
nvm install 0.10

Создайте следующий файл:
touch /var/www/example.com/server.js

Вставьте в него следующее содержимое:
//nodejs.org/api for API docs
//Node.js web server
var http = require(«http»), //Import Node.js modules
url = require(«url»),
path = require(«path»),
fs = require(«fs»);

http.createServer(function(request, response) < //Create server
var name = url.parse(request.url).pathname; //Parse URL
var filename = path.join(process.cwd(), name); //Create filename
fs.readFile(filename, «binary», function(err, file) < //Read file
if(err) < //Tracking Errors
response.writeHead(500, <"Content-Type": "text/plain">);
response.write(err + «n»);
response.end();
return;
>
response.writeHead(200); //Header request response
response.write(file, «binary»); //Sends body response
response.end(); //Signals to server that
>); //header and body sent
>).listen(3000); //Listening port
console.log(«Server is listening on port 3000.») //Terminal output

Запустите новую сессию screen:
screen

Далее нажмите Enter и запустите сервер Node.js:
node server.js

Нажмите комбинацию клавиш Ctrl+A, затем D.

Создание тестового приложения

Создайте файл с тестовыми данными:
touch /var/www/example.com/test.js

И вставьте в него следующие данные:
<!DOCTYPE html>
<html>
<body>

<center>
<p>
The below button is technically dynamic. You are now using Javascript on both the client-side and the server-side.
</p>
</center>
<br>

<center>
<button type=»button»
onclick=»document.getElementById(‘sample’).innerHTML = Date()»>
Display the date and time.
</button>
<p ></p>
</center>

Откройте порт 80 для подключения по http:
iptables -A INPUT -p tcp —dport 80 -j ACCEPT

Перейдите в браузере по вашему домену или ip-адресу. Отобразится следующая страница. Нажмите кнопку Go to the test.js:

Go to the test.js

Если все настроено корректно, с помощью кнопки Display the date and time на новой странице можно вывести текущее время и дату:

Настройка vps ноде js что это

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *