Bagaimana untuk menggunakan pelayan nod dalam EC2

WBOY
Lepaskan: 2024-09-05 06:48:53
asal
215 orang telah melayarinya

How to deploy a node server in EC2

Menggunakan pelayan Node.js pada AWS EC2 membolehkan anda memanfaatkan infrastruktur yang boleh dipercayai, skalabiliti dan fleksibiliti AWS untuk mengehoskan aplikasi anda dengan cekap. Panduan ini akan membawa anda langkah demi langkah melalui menyediakan contoh EC2, memasang alat penting seperti Nginx dan PM2, dan melindungi aplikasi anda dengan HTTPS menggunakan Let's Encrypt. Pada penghujung panduan ini, anda akan mempunyai pelayan Node.js yang berfungsi sepenuhnya yang berjalan pada persekitaran EC2 yang selamat, bersedia untuk mengendalikan trafik pengeluaran.

Garis besar

  • Keperluan
  • Menyediakan Instance EC2
  • Menyambung ke EC2 melalui SSH atau Putty
  • Memasang Pakej dan Alat yang Diperlukan
  • Menyediakan PM2 untuk Aplikasi Node.js
  • Mengkonfigurasi Nginx sebagai Proksi Songsang
  • Mengakses Pelayan Menggunakan IP Awam
  • Memahami Keperluan untuk HTTPS
  • Menyediakan Domain dan Sijil SSL
  • Memasang Certbot untuk SSL dengan Nginx
  • Memetakan Domain ke IP Awam
  • Menguji Pelayan dan Pemeriksaan Akhir

Keperluan

Sebelum bermula, pastikan anda mempunyai perkara berikut:

  • Akaun AWS.
  • Pengetahuan asas tentang baris arahan Linux.
  • Nama domain berdaftar (untuk menyediakan HTTPS).
  • PuTTY (untuk SSH ke dalam contoh EC2 jika anda menggunakan Windows).

Menyediakan EC2 dan Skrip Permulaan untuk Memasang PM2 dan Nginx

  • Log masuk ke Konsol Pengurusan AWS anda.
  • Navigasi ke Papan Pemuka EC2 dan klik pada Instance Pelancaran.
  • Berikan nama untuk contoh.
  • Pilih Pelayan Ubuntu 22.04 LTS (HVM), Jenis Kelantangan SSD.
  • Pilih jenis tika (cth., t2.micro untuk peringkat percuma).
  • Jana sepasang kunci (.pem) dan simpan, kami akan menggunakannya kemudian.
  • Konfigurasikan kumpulan keselamatan untuk membenarkan trafik masuk pada port 22 (SSH), 80 (HTTP) dan 443 (HTTPS).

Apabila melancarkan contoh anda, anda boleh menyediakan skrip data pengguna untuk mengautomasikan pemasangan pakej yang diperlukan.

  • Dalam bahagian Butiran Lanjutan, cari medan "Data pengguna".
  • Pilih "Sebagai teks" dan masukkan skrip data pengguna anda dalam kawasan teks yang disediakan.
#!/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
Salin selepas log masuk

Penjelasan Kod Permulaan

Kemas Kini dan Pemasangan Sistem:

  • kemas kini sudo apt: Mengemas kini senarai pakej untuk Ubuntu.
  • sudo apt install nginx -y: Memasang Nginx, pelayan web.
  • sudo apt-get install curl: Memasang curl, alat untuk memindahkan data dari atau ke pelayan.

Pasang Node.js dan Benang:

  • curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -: Menambah repositori Node.js 18.
  • sudo apt-get install -y nodejs: Memasang Node.js.
  • curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -: Menambah kunci repositori Benang.
  • echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list: Menambah repositori Benang.
  • sudo apt-get update: Mengemas kini senarai pakej untuk memasukkan Benang.
  • sudo apt-get install yarn -y: Memasang Benang, pengurus pakej.

Pasang PM2:

  • sudo npm i -g pm2: Memasang PM2 secara global untuk mengurus aplikasi Node.js.

Sandaran dan Persediaan Konfigurasi Nginx:

  • sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bkp: Menyandarkan fail konfigurasi Nginx lalai.
  • sudo rm /etc/nginx/sites-available/default: Mengalih keluar fail konfigurasi Nginx lalai asal.
  • sudo echo "pelayan { ... }" > /etc/nginx/sites-available/default: Mencipta konfigurasi Nginx baharu:
    • Mendengar pada port 80.
    • Menetapkan nama_pelayan kepada domain atau IP awam.
    • Proksi meminta kepada pelayan bahagian belakang yang berjalan pada http://127.0.0.1:3000.
    • Bahagian yang dikomen untuk menyiarkan fail statik dan kandungan bahagian hadapan.

Alih Keluar Kandungan Nginx Lalai:

  • sudo rm /var/www/html/index.nginx-debian.html: Mengalih keluar halaman alu-aluan Nginx lalai.

Kemas kini Senarai Pakej Lagi:

  • sudo apt-get update: Menjalankan kemas kini lain untuk memastikan semua senarai pakej adalah terkini.

Skrip ini menyediakan persekitaran dengan Nginx, Node.js, Yarn dan PM2 serta mengkonfigurasi Nginx untuk bertindak sebagai proksi terbalik kepada pelayan bahagian belakang yang dijalankan pada port 3000.

Selepas ini klik pada butang Lancarkan contoh untuk mencipta tika.

SSH ke EC2 Menggunakan PuTTY atau Terminal dan Klon Repositori Node.js Anda

Setelah tika berjalan, SSH ke dalam tika EC2 anda menggunakan terminal (untuk macOS/Linux):

ssh -i path/to/your-key.pem ubuntu@<your-ec2-public-ip>
Salin selepas log masuk

Jika anda menggunakan tingkap, anda boleh menggunakan putty untuk log masuk - langkah untuk log masuk.

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
Salin selepas log masuk

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

git clone <your-repo-url>
cd <your-repo-directory>
Salin selepas log masuk

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
Salin selepas log masuk

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

nano ecosystem.config.js
Salin selepas log masuk

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",
    }
  }]
};
Salin selepas log masuk

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
Salin selepas log masuk

You can check the logs using:

pm2 logs
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

Run Certbot to Obtain SSL Certificate:

sudo certbot --nginx -d YOUR_DOMAIN
Salin selepas log masuk

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/
Salin selepas log masuk

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;
    }
}
Salin selepas log masuk

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

nginx -s reload
Salin selepas log masuk

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.

Atas ialah kandungan terperinci Bagaimana untuk menggunakan pelayan nod dalam EC2. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!