Guia Completo para Implementar e Otimizar Servidores Node.js na Vultr com PM2, Nginx e Certbot (2024)

Neste guia abrangente, vamos explorar passo a passo como implementar e otimizar servidores Node.js na Vultr, utilizando ferramentas poderosas como PM2, Nginx e Certbot. Ao seguir este tutorial, você garantirá não apenas a implementação eficiente de seu aplicativo Node.js, mas também a otimização para obter o melhor desempenho e segurança.

Passo 1: Implantação do Servidor na Vultr

1.1 Cadastro e Login na Vultr

Comece criando uma conta na Vultr e faça o login no Portal do Cliente.

1.2 Implantação do Servidor

  1. Acesse a página de Produtos.
  2. No menu lateral, escolha Compute.
  3. Clique no botão "Deploy Server".
  4. Selecione Cloud Compute como o tipo de servidor.
  5. Escolha a região desejada.
  6. Na seção "Server Image", vá para a guia Marketplace Apps e escolha a imagem NodeJS.
  7. Selecione o tamanho do servidor conforme suas necessidades.
  8. Adicione recursos adicionais, se necessário.
  9. Clique em "Deploy Now" para finalizar.

Passo 2: Criando uma Aplicação Node.js

2.1 Inicializando o Projeto

Após a criação do servidor Vultr, siga as etapas para criar uma aplicação Node.js utilizando o framework Express.

mkdir ~/express-demo
cd ~/express-demo
npm init

2.2 Configurando o Express

Instale o Express e crie um arquivo index.js com o seguinte conteúdo:

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("<h1>Hello World, saudações da Vultr</h1>");
});

app.listen(3000, () => {
  console.log("Servidor ouvindo na porta 3000");
});

Inicie a aplicação e teste-a no navegador.

sudo ufw allow 3000
node index.js

Passo 3: Configurando PM2 para Persistência

3.1 Instalação do PM2

Instale globalmente o PM2 e inicie a aplicação em modo cluster.

sudo npm install pm2 -g
pm2 start ~/express-demo -i 4 --name express-demo
pm2 startup
pm2 save

Passo 4: Configurando Nginx como Reverse Proxy

4.1 Instalação do Nginx

Instale o Nginx e configure-o como um servidor proxy reverso para lidar com solicitações HTTP.

sudo apt install nginx
sudo nano /etc/nginx/sites-available/express-demo.conf

Cole o seguinte conteúdo, substituindo "example.com" pelo seu nome de domínio real:

server {
  listen 80;
  listen [::]:80;
  server_name example.com www.example.com;

  location / {
    proxy_pass http://127.0.0.1:3000/;
  }
}

Ative a configuração e reinicie o Nginx.

sudo ln -s /etc/nginx/sites-available/express-demo.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
sudo ufw allow 80/tcp

Passo 5: Instalando Certificados SSL com Certbot

5.1 Permitindo Conexões SSL

Abra a porta 443 para permitir conexões HTTPS.

sudo ufw allow 443/tcp
sudo snap install --classic certbot
sudo certbot --nginx -d example.com -d www.example.com

Teste a conexão HTTPS no navegador.

sudo certbot renew --dry-run

Passo 6: Escalonando Serviços PM2

6.1 Listando Processos PM2

Liste todos os processos PM2 em execução.

pm2 list

6.2 Escalonando para Baixo

Reduza o número de instâncias do serviço Node.js.

pm2 scale express-demo 2

6.3 Escalonando para Cima

Aumente o número de instâncias do serviço Node.js.

pm2 scale express-demo 5

6.4 Comandos Adicionais PM2

  • Parar todos os processos PM2: pm2 stop all
  • Reiniciar todos os processos PM2: pm2 restart all
  • Recarregar suavemente todos os processos PM2: pm2 reload all
  • Monitorar todos os processos PM2: pm2 monit
  • Examinar os logs gerados pelo PM2: pm2 logs

Conclusão

Este guia abordou a implementação detalhada de um servidor Node.js na Vultr, otimizado com PM2, Nginx e Certbot. Ao seguir essas etapas, você garantirá não apenas a presença online de seu aplicativo, mas também sua eficiência, escalabilidade e segurança. Lembre-se de ajustar as configurações conforme suas necessidades específicas.

Guia Completo para Implementar e Otimizar Servidores Node.js na Vultr com PM2, Nginx e Certbot (2024)

FAQs

How to deploy NodeJS app on vultr? ›

Creating a Node. js application
  1. Create a folder to store the project files, and navigate into it. ...
  2. Initialize a Node. ...
  3. Install the express library. ...
  4. Create a file named index. ...
  5. Paste the following content into the index. ...
  6. Save the file, and exit the editor.
  7. Allow port 3000 to listen for incoming connections.
Nov 7, 2023

How to deploy Node js application on Ubuntu server with Nginx? ›

Node. js Deployment
  1. Sign up for Digital Ocean. ...
  2. Create a droplet and log in via ssh. ...
  3. Install Node/NPM. ...
  4. Clone your project from Github. ...
  5. Setup PM2 process manager to keep your app running. ...
  6. Setup ufw firewall. ...
  7. Install NGINX and configure. ...
  8. Add domain in Digital Ocean.

Should you use Nginx with NodeJS? ›

Putting Nginx in front of your Node app allows you to map requests on port 80 though to the port number where you Node app is running. This means your Node app doesn't have to worry about privileges/setuid for the Node. js process and may help to mitigate security flaws and DoS attacks against Node.

How to get free SSL certificate for Node js? ›

Using SSL with NodeJS
  1. Create an environment with the Node. js application server.
  2. Install the Let's Encrypt add-on to generate free SSL certificates for your application. Due to the Node. ...
  3. Create a new app or integrate HTTPS configs into the existing application. ...
  4. Run your application via Web SSH.

How do I setup a Vultr server? ›

Here are the steps to build your Vultr server with RunCloud:
  1. Click on the “Let's get started” button on the RunCloud dashboard to create your first server.
  2. On the next screen, you will see a list of available server providers. Choose Vultr and click on the “Deploy Server Automatically” option.
Feb 7, 2024

How to deploy node js application on web server? ›

Deploy & Run your Node. js application
  1. GIT clone the code in a build folder.
  2. Install dependencies via npm ci.
  3. Configure Supervisord to start and manage the Node.js process.
  4. Reread and update the Supervisord program configuration.
  5. Symlink the build for to the current release folder.
  6. Restart the Node.js process via Supervisord.

How to build and deploy Node js application to Linux server? ›

  1. Configure your Linux deployment target.
  2. Install Mono.
  3. Add user.
  4. Install the application dependencies.
  5. Create and push a Node.js project.
  6. Download and run the template.
  7. Configure the publish task.
  8. Option 1 - Gulp publish task.
Jan 1, 2023

How do I deploy a node JS application for production? ›

How to deploy a Node. js application in production
  1. curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - ...
  2. sudo apt-get install -y nodejs. ...
  3. node --version && npm --version. ...
  4. sudo vi app.js. ...
  5. const express = require('express') const app = express() const port = 3000 app. ...
  6. npm install express. ...
  7. node app.js.
Jul 1, 2022

Should I use Nginx or Apache? ›

NGINX may be your best bet if your website has high traffic levels, like an ecommerce store or cloud storage services. Verdict: Although Apache has multi-processing modules to support multiple processes, NGINX's asynchronous event-driven architecture wins. NGINX is better for high traffic and scalability.

When should you not use node JS? ›

js receives a CPU-bound task: Whenever a heavy request comes to the event loop, Node. js would set all the CPU available to process it first, and then answer other requests queued. That results in slow processing and overall delay in the event loop, which is why Node. js is not recommended for heavy computation.

Why NGINX is better than IIS? ›

Microsoft IIS server is not open source and it comes with its own overhead in terms of cost which is not the case with Nginx as we do not need to purchase a handful of other products in order to get an HTTP server up and running.

Do people still use NGINX? ›

NGINX is a widely used web server and reverse proxy server that is renowned for its high performance and scalability. It was created by Igor Sysoev in 2004 to address the challenge of handling a large number of simultaneous connections, known as the C10k problem.

How to get free domain and SSL certificate? ›

Get full protection for any domain, website and backend system in under 5 minutes by using ZeroSSL, the easiest way to issue free SSL certificates. Get new and existing SSL certificates approved within a matter of seconds using one-step email validation, server uploads or CNAME verification.

How to get free SSL certificate without domain? ›

To get an SSL certificate without a domain, you must provide proof of ownership of the IP address. This is done by verifying that you have control over the server hosting the website associated with the public IP. A public IP address is reachable from the internet.

Are SSL certificates free? ›

The free version of SSL shares SSL certificates among multiple customer domains. Cloudflare also offers customized SSL certificates for enterprise customers. To get a free SSL certificate, domain owners need to sign up for Cloudflare and select an SSL option in their SSL settings.

How do I deploy a Nodejs app to production? ›

How to deploy a Node. js application in production
  1. curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - ...
  2. sudo apt-get install -y nodejs. ...
  3. node --version && npm --version. ...
  4. sudo vi app.js. ...
  5. const express = require('express') const app = express() const port = 3000 app. ...
  6. npm install express. ...
  7. node app.js.
Jul 1, 2022

Where do I deploy my Nodejs app? ›

Node. js applications can easily be deployed on DigitalOcean Droplets or App Platform. Check out this tutorial on how to deploy Node. js on DigitalOcean and this tutorial on how to set up Node.

How do I deploy a node app to VPS? ›

Step-by-step guide for Node. js installation
  1. Step 1: Access your VPS. If you're connecting to the Linux VPS from a Windows OS, you have three options to choose from: ...
  2. Step 2: Update your VPS. Before installing Node. ...
  3. Step 3: Install Node. ...
  4. Step 4: Manage your Node. ...
  5. Step 5: Keep your application running. ...
  6. Step 6: Updating Node.
Feb 8, 2024

How to deploy node js app with database? ›

Deploying a Node. js + MongoDB + Express App on Render
  1. Step 1: Preparing Your Node.js + MongoDB + Express App. Ensure that your Node. ...
  2. Step 2: Create a New Web Service on Render. ...
  3. Step 3: Define Environment Variables. ...
  4. Step 4: Setting Up the Database. ...
  5. Step 5: Deploying Your App. ...
  6. Step 6: Testing Your App.
Oct 30, 2023

References

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5697

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.