EC2에 노드 서버를 배포하는 방법

WBOY
풀어 주다: 2024-09-05 06:48:53
원래의
215명이 탐색했습니다.

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 Management Console에 로그인하세요.
  • 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를 설치합니다.
  • sudo apt-get install 컬: 서버와 데이터를 주고 받는 도구인 컬을 설치합니다.

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 또는 터미널을 사용하여 EC2에 SSH로 접속하고 Node.js 리포지토리를 복제합니다.

인스턴스가 실행되면 터미널(macOS/Linux용)을 사용하여 EC2 인스턴스에 SSH로 연결합니다.

ssh -i path/to/your-key.pem ubuntu@<your-ec2-public-ip>
로그인 후 복사

Windows를 사용하는 경우 퍼티를 사용하여 로그인할 수 있습니다. 로그인 단계입니다.

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!