AWS EC2 に Node.js サーバーをデプロイすると、AWS の信頼できるインフラストラクチャ、スケーラビリティ、柔軟性を活用してアプリケーションを効率的にホストできます。このガイドでは、EC2 インスタンスのセットアップ、Nginx や PM2 などの必須ツールのインストール、Let's Encrypt を使用した HTTPS によるアプリケーションの保護を段階的に説明します。このガイドを終えると、安全な EC2 環境で完全に機能する Node.js サーバーが稼働し、本番トラフィックを処理できるようになります。
始める前に、以下のものがあることを確認してください:
インスタンスを起動するときに、必要なパッケージのインストールを自動化するユーザー データ スクリプトを提供できます。
#!/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
このスクリプトは、Nginx、Node.js、Yarn、PM2 を使用した環境をセットアップし、ポート 3000 で実行されているバックエンド サーバーに対するリバース プロキシとして機能するように Nginx を構成します。
この後、インスタンスの起動 ボタンをクリックしてインスタンスを作成します。
インスタンスが実行されたら、ターミナル (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..
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).
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.
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.
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
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
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.
To set up HTTPS, you need:
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
Ensure that your domain/subdomain is correctly mapped to your EC2 instance's public IP using A records in your domain DNS settings.
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 サイトの他の関連記事を参照してください。