Heim > Web-Frontend > js-Tutorial > Hauptteil

So stellen Sie einen Knotenserver in EC2 bereit

WBOY
Freigeben: 2024-09-05 06:48:53
Original
270 Leute haben es durchsucht

How to deploy a node server in EC2

Durch die Bereitstellung eines Node.js-Servers auf AWS EC2 können Sie die zuverlässige Infrastruktur, Skalierbarkeit und Flexibilität von AWS nutzen, um Ihre Anwendung effizient zu hosten. Diese Anleitung führt Sie Schritt für Schritt durch die Einrichtung einer EC2-Instanz, die Installation wichtiger Tools wie Nginx und PM2 und die Sicherung Ihrer Anwendung mit HTTPS mithilfe von Let's Encrypt. Am Ende dieses Leitfadens verfügen Sie über einen voll funktionsfähigen Node.js-Server, der in einer sicheren EC2-Umgebung ausgeführt wird und für die Verarbeitung des Produktionsdatenverkehrs bereit ist.

Gliederung

  • Anforderungen
  • EC2-Instanz einrichten
  • Verbindung zu EC2 über SSH oder Putty herstellen
  • Notwendige Pakete und Tools installieren
  • Einrichten von PM2 für die Node.js-Anwendung
  • Nginx als Reverse-Proxy konfigurieren
  • Zugriff auf den Server über öffentliche IP
  • Die Notwendigkeit von HTTPS verstehen
  • Domänen- und SSL-Zertifikate einrichten
  • Certbot für SSL mit Nginx installieren
  • Domäne einer öffentlichen IP zuordnen
  • Testen des Servers und abschließende Kontrollen

Anforderungen

Bevor Sie beginnen, stellen Sie sicher, dass Sie Folgendes haben:

  • Ein AWS-Konto.
  • Grundkenntnisse der Linux-Befehlszeile.
  • Ein registrierter Domänenname (zum Einrichten von HTTPS).
  • PuTTY (für SSH in die EC2-Instanz, wenn Sie Windows verwenden).

Einrichten von EC2 und anfänglichem Skript zur Installation von PM2 und Nginx

  • Melden Sie sich bei Ihrer AWS-Managementkonsole an.
  • Navigieren Sie zum EC2-Dashboard und klicken Sie auf Instanz starten.
  • Geben Sie einen Namen für die Instanz an.
  • Wählen Sie Ubuntu Server 22.04 LTS (HVM), SSD-Volume-Typ.
  • Wählen Sie einen Instanztyp (z. B. t2.micro für die kostenlose Stufe).
  • Generieren Sie ein Schlüsselpaar (.pem) und speichern Sie es, wir werden es später verwenden.
  • Konfigurieren Sie die Sicherheitsgruppe so, dass eingehender Datenverkehr auf den Ports 22 (SSH), 80 (HTTP) und 443 (HTTPS) zugelassen wird.

Beim Starten Ihrer Instanz können Sie ein Benutzerdatenskript bereitstellen, um die Installation der erforderlichen Pakete zu automatisieren.

  • Suchen Sie im Abschnitt „Erweiterte Details“ das Feld „Benutzerdaten“.
  • Wählen Sie „Als Text“ und geben Sie Ihr Benutzerdatenskript in den dafür vorgesehenen Textbereich ein.
#!/bin/bash
sudo apt update
sudo apt install nginx -y
sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update
sudo apt-get install yarn -y
sudo npm i -g pm2
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bkp
sudo rm /etc/nginx/sites-available/default
sudo echo "server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # The server_name can be changed to your domain or left as-is for IP-based access
    server_name YOUR_DOMAIN;  # Use your domain or public IP if no domain is configured

    # Proxy requests to the backend server running on port 3000
    location / {
        proxy_pass http://127.0.0.1:3000;  # Your backend port here
        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;
        proxy_redirect off;
    }

    # Optional: serve static files directly from a directory if needed
    # location /static {
    #     alias /path/to/static/files;  # Uncomment and set path if you have static files
    #     expires 30d;
    #     access_log off;
    # }

    # This is commented out because we are not serving any frontend files from /var/www/html
    # root /var/www/html;
    # index index.html index.htm index.nginx-debian.html;
}
" > /etc/nginx/sites-available/default
sudo rm /var/www/html/index.nginx-debian.html
sudo apt-get update
Nach dem Login kopieren

Erläuterung des ursprünglichen Codes

Systemaktualisierungen und Installationen:

  • sudo apt update: Aktualisiert die Paketliste für Ubuntu.
  • sudo apt install nginx -y: Installiert Nginx, einen Webserver.
  • sudo apt-get install curl: Installiert Curl, ein Tool zum Übertragen von Daten von oder zu einem Server.

Installieren Sie Node.js und Yarn:

  • curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -: Fügt das Node.js 18-Repository hinzu.
  • sudo apt-get install -y nodejs: Installiert Node.js.
  • curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -: Fügt den Yarn-Repository-Schlüssel hinzu.
  • echo „deb https://dl.yarnpkg.com/debian/stable main“ | sudo tee /etc/apt/sources.list.d/yarn.list: Fügt Yarn-Repository hinzu.
  • sudo apt-get update: Aktualisiert Paketlisten, um Yarn einzuschließen.
  • sudo apt-get install Yarn -y: Installiert Yarn, einen Paketmanager.

Installieren Sie PM2:

  • sudo npm i -g pm2: Installiert PM2 global, um Node.js-Anwendungen zu verwalten.

Sicherung und Einrichtung der Nginx-Konfiguration:

  • sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bkp: Sichert die Standard-Nginx-Konfigurationsdatei.
  • sudo rm /etc/nginx/sites-available/default: Entfernt die ursprüngliche Standard-Nginx-Konfigurationsdatei.
  • sudo echo "server { ... }" > /etc/nginx/sites-available/default: Erstellt eine neue Nginx-Konfiguration:
    • Hört auf Port 80.
    • Setzt server_name auf die Domäne oder öffentliche IP.
    • Proxy-Anfragen an einen Backend-Server, der unter http://127.0.0.1:3000 läuft.
    • Auskommentierte Abschnitte für die Bereitstellung statischer Dateien und Frontend-Inhalte.

Standard-Nginx-Inhalt entfernen:

  • sudo rm /var/www/html/index.nginx-debian.html: Entfernt die standardmäßige Nginx-Willkommensseite.

Paketliste erneut aktualisieren:

  • sudo apt-get update: Führt ein weiteres Update aus, um sicherzustellen, dass alle Paketlisten aktuell sind.

Dieses Skript richtet eine Umgebung mit Nginx, Node.js, Yarn und PM2 ein und konfiguriert Nginx so, dass es als Reverse-Proxy für einen Backend-Server fungiert, der auf Port 3000 ausgeführt wird.

Klicken Sie anschließend auf die Schaltfläche Instanz starten, um eine Instanz zu erstellen.

SSH in EC2 mit PuTTY oder Terminal und klonen Sie Ihr Node.js-Repository

Sobald die Instanz ausgeführt wird, stellen Sie über das Terminal eine SSH-Verbindung zu Ihrer EC2-Instanz her (für macOS/Linux):

ssh -i path/to/your-key.pem ubuntu@<your-ec2-public-ip>
Nach dem Login kopieren

Wenn Sie Windows verwenden, können Sie sich mit Putty anmelden – Schritte zum Anmelden.

After that it may ask for username which is usually by default - "ubuntu" if not set anything else.

Next use the following command to switch to the root user:

sudo su
Nach dem Login kopieren

Clone your Node.js application from GitHub or any other repository:

git clone <your-repo-url>
cd <your-repo-directory>
Nach dem Login kopieren

Switch to your prodution branch, pull the latest code and install node_modules.

Once done return back to the main directory using cd..

Setting Up ecosystem.config.js and Starting the Server with PM2

PM2 is a popular process manager for Node.js that keeps your application running in the background and helps with load balancing and monitoring.

Create ecosystem.config.js file in your project root:

touch ecosystem.config.js
Nach dem Login kopieren

Open the file in a text editor and add your configuration:

nano ecosystem.config.js
Nach dem Login kopieren

Add the configuration and save the file:

module.exports = {
  apps: [{
    name: "project_name",
    script: "npm start",
    cwd: "/home/ubuntu/repo",
    env: {
      "MONGO_URL": "mongodb+srv://<credentials>",
      "PORT": 3000,
      "NODE_ENV": "prod",
    }
  }]
};
Nach dem Login kopieren

Save and exit the editor (for nano, press Ctrl + X, then Y to confirm saving, and Enter to exit).

Explanation of ecosystem.config.js File

The ecosystem.config.js file is a configuration file for PM2, a process manager for Node.js applications. It defines how the application should be managed, including its environment variables, working directory, and startup script.

Breakdown of the Configuration:

  • module.exports: Exports the configuration object so that PM2 can use it to manage the application.

  • apps: An array of application configurations. This allows PM2 to manage multiple applications using a single configuration file.

    • name: "project_name" The name of the application, as it will appear in PM2's process list. You can set this to your project name.
    • script: "npm start" The command to run the application. Here, it uses npm start to start the application, which typically runs the start script defined in your package.json.
    • cwd: "/home/ubuntu/repo" The "Current Working Directory" where PM2 will look for the application. This is the directory path where your Node.js application code (repository) is located.
    • env: An object defining environment variables that will be available to the application when it is running. These variables can be accessed in your Node.js code using process.env.

Let's move next to starting our server:

Start the Application Using PM2:

pm2 start ecosystem.config.js
Nach dem Login kopieren

You can check the logs using:

pm2 logs
Nach dem Login kopieren

Accessing the Server by Changing Security Rules Using Public IP

Ensure your security group allows inbound traffic on port 3000 (or any port your server is running on). Access your server using:

http://<your-ec2-public-ip>:3000
Nach dem Login kopieren

The Problem with HTTP Server and the Need for HTTPS

HTTP is not secure for transmitting sensitive data. HTTPS, on the other hand, ensures that all data transmitted between the server and client is encrypted. Therefore, it's essential to secure your Node.js server with HTTPS, especially for production environments.

Requirements for HTTPS: Domain and SSL

To set up HTTPS, you need:

  • A domain name pointing to your EC2 public IP.
  • SSL certificate to encrypt the traffic.

SSL Using Certbot and Setting Up Nginx

Install Certbot on EC2:

sudo apt install certbot python3-certbot-nginx -y
Nach dem Login kopieren

Run Certbot to Obtain SSL Certificate:

sudo certbot --nginx -d YOUR_DOMAIN
Nach dem Login kopieren

Follow the prompts to complete the certificate installation. Certbot will automatically update your Nginx configuration to redirect HTTP traffic to HTTPS.

You can check your updated nginx config. Go to this directory:

cd /etc/nginx/sites-available/
Nach dem Login kopieren

Open the default file using nano, and it should look something like this:

server {
    listen 80;
    server_name YOUR_DOMAIN;

    # Redirect HTTP to HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name YOUR_DOMAIN;

    ssl_certificate /etc/letsencrypt/live/YOUR_DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/YOUR_DOMAIN/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}
Nach dem Login kopieren

After SSL setup it should reload Nginx server automatically but you can manually reload using:

nginx -s reload
Nach dem Login kopieren

Domain Mapping to Public IP

Ensure that your domain/subdomain is correctly mapped to your EC2 instance's public IP using A records in your domain DNS settings.

Testing the Server and Finishing Up

Visit https://YOUR_DOMAIN in your browser to verify the HTTPS setup. Your Node.js server should now be accessible securely via HTTPS.

Das obige ist der detaillierte Inhalt vonSo stellen Sie einen Knotenserver in EC2 bereit. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!