찾다
웹 프론트엔드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 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>
</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>
</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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
JavaScript : 웹 언어의 다양성 탐색JavaScript : 웹 언어의 다양성 탐색Apr 11, 2025 am 12:01 AM

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

JavaScript의 진화 : 현재 동향과 미래 전망JavaScript의 진화 : 현재 동향과 미래 전망Apr 10, 2025 am 09:33 AM

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

Demystifying JavaScript : 그것이하는 일과 중요한 이유Demystifying JavaScript : 그것이하는 일과 중요한 이유Apr 09, 2025 am 12:07 AM

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

Python 또는 JavaScript가 더 좋습니까?Python 또는 JavaScript가 더 좋습니까?Apr 06, 2025 am 12:14 AM

Python은 데이터 과학 및 기계 학습에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명하며 데이터 분석 및 웹 개발에 적합합니다. 2. JavaScript는 프론트 엔드 개발의 핵심입니다. Node.js는 서버 측 프로그래밍을 지원하며 풀 스택 개발에 적합합니다.

JavaScript를 어떻게 설치합니까?JavaScript를 어떻게 설치합니까?Apr 05, 2025 am 12:16 AM

JavaScript는 이미 최신 브라우저에 내장되어 있기 때문에 설치가 필요하지 않습니다. 시작하려면 텍스트 편집기와 브라우저 만 있으면됩니다. 1) 브라우저 환경에서 태그를 통해 HTML 파일을 포함하여 실행하십시오. 2) Node.js 환경에서 Node.js를 다운로드하고 설치 한 후 명령 줄을 통해 JavaScript 파일을 실행하십시오.

Quartz에서 작업이 시작되기 전에 알림을 보내는 방법은 무엇입니까?Quartz에서 작업이 시작되기 전에 알림을 보내는 방법은 무엇입니까?Apr 04, 2025 pm 09:24 PM

쿼츠 타이머를 사용하여 작업을 예약 할 때 미리 쿼츠에서 작업 알림을 보내는 방법 작업의 실행 시간은 CRON 표현식에 의해 설정됩니다. 지금...

JavaScript에서 생성자의 프로토 타입 체인에서 함수의 매개 변수를 얻는 방법은 무엇입니까?JavaScript에서 생성자의 프로토 타입 체인에서 함수의 매개 변수를 얻는 방법은 무엇입니까?Apr 04, 2025 pm 09:21 PM

JavaScript 프로그래밍에서 JavaScript의 프로토 타입 체인에서 함수 매개 변수를 얻는 방법 프로토 타입 체인의 기능 매개 변수를 이해하고 조작하는 방법은 일반적이고 중요한 작업입니다 ...

Wechat Mini 프로그램 웹 뷰에서 Vue.js 동적 스타일 변위가 실패한 이유는 무엇입니까?Wechat Mini 프로그램 웹 뷰에서 Vue.js 동적 스타일 변위가 실패한 이유는 무엇입니까?Apr 04, 2025 pm 09:18 PM

WeChat 애플릿 웹 뷰에서 vue.js를 사용하는 동적 스타일 변위 실패가 vue.js를 사용하는 이유를 분석합니다.

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 Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.