ホームページ ウェブフロントエンド jsチュートリアル EC2にノードサーバーをデプロイする方法

EC2にノードサーバーをデプロイする方法

Sep 05, 2024 am 06:48 AM

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 を使用している場合、EC2 インスタンスへの SSH 用)。

PM2 と Nginx をインストールするための EC2 と初期スクリプトのセットアップ

  • AWS マネジメントコンソールにログインします。
  • EC2 ダッシュボードに移動し、[Launch Instance] をクリックします。
  • インスタンスの名前を入力します。
  • 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: Web サーバーである Nginx をインストールします。
  • sudo apt-get installcurl: サーバーとの間でデータを転送するためのツール、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/安定したメイン" | sudo tee /etc/apt/sources.list.d/yarn.list: Yarn リポジトリを追加します。
  • sudo apt-get update: Yarn を含むようにパッケージ リストを更新します。
  • sudo apt-get installyarn -y: パッケージマネージャーである Yarn をインストールします。

PM2 をインストールします。

  • sudo npm i -g pm2: Node.js アプリケーションを管理するために PM2 をグローバルにインストールします。

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 を使用した環境をセットアップし、ポート 3000 で実行されているバックエンド サーバーに対するリバース プロキシとして機能するように Nginx を構成します。

この後、インスタンスの起動 ボタンをクリックしてインスタンスを作成します。

PuTTY またはターミナルを使用して EC2 に SSH 接続し、Node.js リポジトリのクローンを作成します

インスタンスが実行されたら、ターミナル (macOS/Linux の場合) を使用して EC2 インスタンスに SSH 接続します。

ssh -i path/to/your-key.pem ubuntu@<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>
ログイン後にコピー

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",
    }
  }]
};
ログイン後にコピー

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
ログイン後にコピー

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 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

フロントエンドのサーマルペーパーレシートのために文字化けしたコード印刷に遭遇した場合はどうすればよいですか? フロントエンドのサーマルペーパーレシートのために文字化けしたコード印刷に遭遇した場合はどうすればよいですか? Apr 04, 2025 pm 02:42 PM

フロントエンドのサーマルペーパーチケット印刷のためのよくある質問とソリューションフロントエンド開発におけるチケット印刷は、一般的な要件です。しかし、多くの開発者が実装しています...

javascriptの分解:それが何をするのか、なぜそれが重要なのか javascriptの分解:それが何をするのか、なぜそれが重要なのか Apr 09, 2025 am 12:07 AM

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

誰がより多くのPythonまたはJavaScriptを支払われますか? 誰がより多くのPythonまたはJavaScriptを支払われますか? Apr 04, 2025 am 12:09 AM

スキルや業界のニーズに応じて、PythonおよびJavaScript開発者には絶対的な給与はありません。 1. Pythonは、データサイエンスと機械学習でさらに支払われる場合があります。 2。JavaScriptは、フロントエンドとフルスタックの開発に大きな需要があり、その給与もかなりです。 3。影響要因には、経験、地理的位置、会社の規模、特定のスキルが含まれます。

Shiseidoの公式Webサイトのように、視差スクロールと要素のアニメーション効果を実現する方法は?
または:
Shiseidoの公式Webサイトのようにスクロールするページを伴うアニメーション効果をどのように実現できますか? Shiseidoの公式Webサイトのように、視差スクロールと要素のアニメーション効果を実現する方法は? または: Shiseidoの公式Webサイトのようにスクロールするページを伴うアニメーション効果をどのように実現できますか? Apr 04, 2025 pm 05:36 PM

この記事の視差スクロールと要素のアニメーション効果の実現に関する議論では、Shiseidoの公式ウェブサイト(https://www.shisido.co.co.jp/sb/wonderland/)と同様の達成方法について説明します。

JavaScriptは学ぶのが難しいですか? JavaScriptは学ぶのが難しいですか? Apr 03, 2025 am 12:20 AM

JavaScriptを学ぶことは難しくありませんが、挑戦的です。 1)変数、データ型、関数などの基本概念を理解します。2)非同期プログラミングをマスターし、イベントループを通じて実装します。 3)DOM操作を使用し、非同期リクエストを処理することを約束します。 4)一般的な間違いを避け、デバッグテクニックを使用します。 5)パフォーマンスを最適化し、ベストプラクティスに従ってください。

JavaScriptの進化:現在の傾向と将来の見通し JavaScriptの進化:現在の傾向と将来の見通し Apr 10, 2025 am 09:33 AM

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

JavaScriptを使用して、同じIDを持つArray要素を1つのオブジェクトにマージする方法は? JavaScriptを使用して、同じIDを持つArray要素を1つのオブジェクトにマージする方法は? Apr 04, 2025 pm 05:09 PM

同じIDを持つ配列要素をJavaScriptの1つのオブジェクトにマージする方法は?データを処理するとき、私たちはしばしば同じIDを持つ必要性に遭遇します...

フロントエンド開発でVSCodeと同様に、パネルドラッグアンドドロップ調整機能を実装する方法は? フロントエンド開発でVSCodeと同様に、パネルドラッグアンドドロップ調整機能を実装する方法は? Apr 04, 2025 pm 02:06 PM

フロントエンドのVSCodeと同様に、パネルドラッグアンドドロップ調整機能の実装を調べます。フロントエンド開発では、VSCODEと同様のVSCODEを実装する方法...

See all articles