0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWSのEC2を使って、Nodeサーバーを構築してみようpart4

Last updated at Posted at 2024-11-18

こんにちは!今回はpart4ということで、サーバーにNode.jsアプリケーションをデプロイします。

はじめに

▼開発環境

  • Windows PC
  • Windows Powershell
  • VS code
  • node v21.7.3

Nodeアプリケーションをローカル環境に作成

expressを使用してnodeアプリケーションを作成していきます。
※nodeをインストールできていない人は、こちらを参考にしてください。

①プロジェクトディレクトリに必要なパッケージをインストール

npm init -y
npm install express

②コードを用意する

今回はexpressを使用してnodeアプリケーションを作成しています。ポート番号は3000番を指定しています。

server.js
const express = require('express');
const app = express();
//通常はenvファイルに記載する
const port = 3000

// サーバーの起動
app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
});

app.get('/', (req, res) => {
      res.send('Hello World!');
});

③サーバーを起動する

起動後、Server is running on port 3000と表示されれば正常に起動できています。

node server.js

http://localhost:3000にブラウザからアクセスする

Hello world!と画面に表示されていればOKです!

スクリーンショット 2024-11-18 134535.png

EC2へのデプロイ

ローカル環境に作成したnodeアプリケーションをEC2へデプロイします。

ステップ1: フォルダをEC2に転送する

デプロイするプロジェクトの構成は以下の通りです:

node_server/
├── node_modules/ # このフォルダは転送不要
├── package-lock.json
├── package.json
└── server.js

node_modules フォルダは転送せず、EC2上で npm install を実行して依存パッケージをインストールします。

①プロジェクトのディレクトリ直下にexclude.txtを作成する

(exclude.txtの中身)

node_modules

②一時フォルダを作成してコピーする

(例: プロジェクトディレクトリの位置:C:\Users\user\Programming\node_server)
プロジェクトのディレクトリまで移動し下記コマンドを実行する。

PS C:\Users\user\Programming\node_server> xcopy "C:\Users\user\Programming\node_server" "C:\Users\user\Programming\temp_deploy" /E /I /H /exclude:exclude.txt

③一時フォルダからSCPを実行

scp -i "秘密鍵のパス" -r "C:\Users\user\Programming\temp_deploy" ec2-user@パブリックIP:/home/ec2-user/

④EC2へログインし、デプロイしたフォルダを確認

以前作成したEC2へログインをします。ログイン方法はこちらをご覧ください!

lsコマンドを入力し、下記のようにtemp_deployが表示されます。
cdコマンドでtemp_deployフォルダに移動し、再度lsコマンドを入力してください。
下記画像と同じファイルが表示されます。

スクリーンショット 2024-11-18 212618.png

デプロイできてることが確認出来たら、パッケージのインストールを行います。
temp_deployフォルダに移動し、コマンドを実行する。実行後、lsコマンドで確認すると、node_modulesフォルダが確認できます。

npm install

⑤Nginx設定ファイルの編集

nanoコマンドでNginx設定ファイルを編集する。

[ec2-user@ip-172-31-44-164 temp_deploy]$ sudo nano /etc/nginx/conf.d/default.conf

設定ファイルが開けたら下記の設定を追加する。
この設定は、80番ポート(HTTP)でリクエストを受け付け、すべてのリクエストを3001番ポート(nodeアプリケーションが起動してるサーバー)へプロキシ転送をしています。

conf
server {
    listen 80;

    location / {
        proxy_pass http://localhost: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;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

設置ファイル編集後にNginxの再起動を行います。

sudo systemctl restart nginx

⑥Nodeサーバーを立ち上げる

最後に、Nodeサーバーを起動させます。
コマンド実行後、Server is running on port 3000と表示されます。

node server.js

サイトにもアクセスしてみましょう。作成したインスタンスのIPアドレスをブラウザの検索バーに入力します。
Hello Wolrd!と画面に表示されれば正常にNodeサーバーが起動できています。

トラブルシューティング

▼ "require is not defined in ES module scope"エラーの場合

package.jsonから "type": "module" を削除するか、importを使用します。

server.js
import express from 'express';

▼ ポートが使用中の場合

使用中のプロセスを確認し、必要に応じて終了します。

sudo lsof -i :3000

▼ パーミッションエラーの場合

sudo chown -R ec2-user:ec2-user /path/to/directory

おわりに

以上でAWSのEC2を使って、Nodeサーバーを構築してみようは終わりになります。
最後までご覧いただきありがとうございました!
次回は、SSL/TLS証明書の導入を行っていきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?