検索
ホームページウェブフロントエンド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 を使用している場合、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>
</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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python vs. JavaScript:コミュニティ、ライブラリ、リソースPython vs. JavaScript:コミュニティ、ライブラリ、リソースApr 15, 2025 am 12:16 AM

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

C/CからJavaScriptへ:すべてがどのように機能するかC/CからJavaScriptへ:すべてがどのように機能するかApr 14, 2025 am 12:05 AM

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

JavaScriptエンジン:実装の比較JavaScriptエンジン:実装の比較Apr 13, 2025 am 12:05 AM

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

ブラウザを超えて:現実世界のJavaScriptブラウザを超えて:現実世界のJavaScriptApr 12, 2025 am 12:06 AM

現実世界におけるJavaScriptのアプリケーションには、サーバー側のプログラミング、モバイルアプリケーション開発、モノのインターネット制御が含まれます。 2。モバイルアプリケーションの開発は、ReactNativeを通じて実行され、クロスプラットフォームの展開をサポートします。 3.ハードウェアの相互作用に適したJohnny-Fiveライブラリを介したIoTデバイス制御に使用されます。

next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合)next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合)Apr 11, 2025 am 08:23 AM

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます

next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合)next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合)Apr 11, 2025 am 08:22 AM

この記事では、許可によって保護されたバックエンドとのフロントエンド統合を示し、next.jsを使用して機能的なedtech SaaSアプリケーションを構築します。 FrontEndはユーザーのアクセス許可を取得してUIの可視性を制御し、APIリクエストがロールベースに付着することを保証します

JavaScript:Web言語の汎用性の調査JavaScript:Web言語の汎用性の調査Apr 11, 2025 am 12:01 AM

JavaScriptは、現代のWeb開発のコア言語であり、その多様性と柔軟性に広く使用されています。 1)フロントエンド開発:DOM操作と最新のフレームワーク(React、Vue.JS、Angularなど)を通じて、動的なWebページとシングルページアプリケーションを構築します。 2)サーバー側の開発:node.jsは、非ブロッキングI/Oモデルを使用して、高い並行性とリアルタイムアプリケーションを処理します。 3)モバイルおよびデスクトップアプリケーション開発:クロスプラットフォーム開発は、反応および電子を通じて実現され、開発効率を向上させます。

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

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

See all articles

ホット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衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。