搜索
首页web前端js教程如何在EC2中部署节点服务器

How to deploy a node server in EC2

在 AWS EC2 上部署 Node.js 服务器使您可以利用 AWS 的可靠基础设施、可扩展性和灵活性来高效托管您的应用程序。本指南将引导您逐步设置 EC2 实例、安装 Nginx 和 PM2 等基本工具,以及使用 Let's Encrypt 通过 HTTPS 保护您的应用程序。在本指南结束时,您将拥有一个在安全的 EC2 环境上运行的功能齐全的 Node.js 服务器,准备好处理生产流量。

大纲

  • 要求
  • 设置 EC2 实例
  • 通过 SSH 或 Putty 连接到 EC2
  • 安装必要的软件包和工具
  • 为 Node.js 应用程序设置 PM2
  • 将 Nginx 配置为反向代理
  • 使用公网IP访问服务器
  • 了解 HTTPS 的需求
  • 设置域名和 SSL 证书
  • 使用 Nginx 安装 SSL Certbot
  • 将域名映射到公共 IP
  • 测试服务器和最终检查

要求

开始之前,请确保您具备以下条件:

  • AWS 帐户。
  • Linux 命令行基础知识。
  • 注册域名(用于设置 HTTPS)。
  • PuTTY(如果您使用的是 Windows,则用于通过 SSH 访问 EC2 实例)。

设置 EC2 和初始脚本以安装 PM2 和 Nginx

  • 登录您的 AWS 管理控制台。
  • 导航到 EC2 仪表板并单击启动实例。
  • 提供实例的名称。
  • 选择 Ubuntu Server 22.04 LTS (HVM)、SSD 卷类型。
  • 选择实例类型(例如,t2.micro 表示免费套餐)。
  • 生成密钥对(.pem)并保存,稍后我们会用到。
  • 配置安全组以允许端口 22 (SSH)、80 (HTTP) 和 443 (HTTPS) 上的入站流量。

启动实例时,您可以提供用户数据脚本来自动安装必要的软件包。

  • 在“高级详细信息”部分中,找到“用户数据”字段。
  • 选择“作为文本”并在提供的文本区域中输入您的用户数据脚本。
#!/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

初始代码说明

系统更新和安装:

  • sudo apt update:更新 Ubuntu 的软件包列表。
  • sudo apt install nginx -y:安装 Nginx,一个 Web 服务器。
  • sudo apt-get install curl:安装curl,一个从服务器传输数据或向服务器传输数据的工具。

安装 Node.js 和 Yarn:

  • 卷曲-sL https://deb.nodesource.com/setup_18.x | sudo -E bash -:添加 Node.js 18 存储库。
  • sudo apt-get install -y nodejs:安装 Node.js。
  • 卷曲-sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -:添加 Yarn 存储库密钥。
  • echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list:添加 Yarn 存储库。
  • sudo apt-get update:更新包列表以包含 Yarn。
  • sudo apt-get install yarn -y:安装 Yarn,一个包管理器。

安装PM2:

  • sudo npm i -g pm2:全局安装 PM2 以管理 Node.js 应用程序。

Nginx 配置备份和设置:

  • sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bkp:备份默认的 Nginx 配置文件。
  • sudo rm /etc/nginx/sites-available/default:删除原来默认的Nginx配置文件。
  • sudo echo“服务器{...}”> /etc/nginx/sites-available/default:创建新的 Nginx 配置:
    • 监听端口 80。
    • 将 server_name 设置为域或公共 IP。
    • 将请求代理到在 http://127.0.0.1:3000 上运行的后端服务器。
    • 用于提供静态文件和前端内容的注释部分。

删除默认的 Nginx 内容:

  • sudo rm /var/www/html/index.nginx-debian.html:删除默认的 Nginx 欢迎页面。

再次更新包列表:

  • sudo apt-get update:运行另一个更新以确保所有软件包列表都是最新的。

此脚本设置一个包含 Nginx、Node.js、Yarn 和 PM2 的环境,并将 Nginx 配置为充当在端口 3000 上运行的后端服务器的反向代理。

之后点击启动实例按钮来创建实例。

使用 PuTTY 或终端通过 SSH 连接到 EC2 并克隆您的 Node.js 存储库

实例运行后,使用终端通过 SSH 连接到您的 EC2 实例(适用于 macOS/Linux):

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

如果您使用的是 Windows,您可以使用 putty 登录 - 登录步骤。

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

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

git clone <your-repo-url>
cd <your-repo-directory>
</your-repo-directory></your-repo-url>

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

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

nano ecosystem.config.js

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",
    }
  }]
};
</credentials>

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

You can check the logs using:

pm2 logs

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
</your-ec2-public-ip>

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

Run Certbot to Obtain SSL Certificate:

sudo certbot --nginx -d YOUR_DOMAIN

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/

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;
    }
}

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

nginx -s reload

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.

以上是如何在EC2中部署节点服务器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在JavaScript中替换字符串字符在JavaScript中替换字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

构建您自己的Ajax Web应用程序构建您自己的Ajax Web应用程序Mar 09, 2025 am 12:11 AM

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

如何创建和发布自己的JavaScript库?如何创建和发布自己的JavaScript库?Mar 18, 2025 pm 03:12 PM

文章讨论了创建,发布和维护JavaScript库,专注于计划,开发,测试,文档和促销策略。

如何在浏览器中优化JavaScript代码以进行性能?如何在浏览器中优化JavaScript代码以进行性能?Mar 18, 2025 pm 03:14 PM

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

如何使用浏览器开发人员工具有效调试JavaScript代码?如何使用浏览器开发人员工具有效调试JavaScript代码?Mar 18, 2025 pm 03:16 PM

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

jQuery矩阵效果jQuery矩阵效果Mar 10, 2025 am 12:52 AM

将矩阵电影特效带入你的网页!这是一个基于著名电影《黑客帝国》的酷炫jQuery插件。该插件模拟了电影中经典的绿色字符特效,只需选择一张图片,插件就会将其转换为充满数字字符的矩阵风格画面。快来试试吧,非常有趣! 工作原理 插件将图片加载到画布上,读取像素和颜色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地读取图片的矩形区域,并利用jQuery计算每个区域的平均颜色。然后,使用

如何构建简单的jQuery滑块如何构建简单的jQuery滑块Mar 11, 2025 am 12:19 AM

本文将引导您使用jQuery库创建一个简单的图片轮播。我们将使用bxSlider库,它基于jQuery构建,并提供许多配置选项来设置轮播。 如今,图片轮播已成为网站必备功能——一图胜千言! 决定使用图片轮播后,下一个问题是如何创建它。首先,您需要收集高质量、高分辨率的图片。 接下来,您需要使用HTML和一些JavaScript代码来创建图片轮播。网络上有很多库可以帮助您以不同的方式创建轮播。我们将使用开源的bxSlider库。 bxSlider库支持响应式设计,因此使用此库构建的轮播可以适应任何

如何使用Angular上传和下载CSV文件如何使用Angular上传和下载CSV文件Mar 10, 2025 am 01:01 AM

数据集对于构建API模型和各种业务流程至关重要。这就是为什么导入和导出CSV是经常需要的功能。在本教程中,您将学习如何在Angular中下载和导入CSV文件

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版