웹사이트 검색

Debian 10에 Node.js를 설치하고 Nginx를 프런트엔드 프록시 서버로 구성하는 방법


이 페이지에서

  1. 전제 조건
  2. 시작하기\n
  3. Node.js 설치
  4. Node.js 애플리케이션 만들기\n
  5. PM2 설치 및 구성
  6. Nginx를 Node.js용 역방향 프록시로 구성\n
  7. Node.js 애플리케이션에 액세스\n
  8. 결론

Node.js는 동적이고 응답성이 뛰어난 서버측 콘텐츠를 제공하는 데 사용할 수 있는 무료 오픈 소스 JavaScript 플랫폼입니다. Chrome의 V8 JavaScript 엔진을 기반으로 하며 웹 브라우저 외부에서 JavaScript 코드를 실행할 수 있습니다. Linux, FreeBSD, Windows 및 macOS를 포함한 여러 운영 체제에서 실행할 수 있습니다. Node.js는 Apache 및 Nginx와 같은 다른 웹 서버에서도 작동합니다.

이 튜토리얼에서는 백엔드 요청을 처리하도록 Node.js를 설치 및 구성하는 방법과 Debian 10에서 프런트 엔드 요청을 처리하도록 Nginx를 구성하는 방법을 배웁니다.

전제 조건

  • Debian 10을 실행하는 서버.\n
  • 서버에 루트 암호가 구성되어 있습니다.\n

시작하기

먼저 시스템을 최신 버전으로 업데이트하는 것이 좋습니다. 다음 명령으로 수행할 수 있습니다.

apt-get update -y
apt-get upgrade -y

서버가 업데이트되면 다시 시작하여 변경 사항을 적용하십시오.

Node.js 설치

기본적으로 Node.js의 최신 버전은 Debian 10 기본 리포지토리에서 사용할 수 없습니다. 따라서 스크립트에서 설치해야 합니다.

먼저 다음 명령으로 curl을 설치합니다.

apt-get install curl -y

그런 다음 다음 명령을 사용하여 Node.js 설치 스크립트를 다운로드하고 설치합니다.

curl -sL https://deb.nodesource.com/setup_12.x | bash -

설치가 완료되면 다음 명령을 사용하여 Node.js를 설치할 수 있습니다.

apt-get install nodejs -y

설치가 성공적으로 완료되면 다음 명령을 사용하여 Node.js 버전을 확인할 수 있습니다.

nodejs --version

다음 출력에 Node.js 버전이 표시되어야 합니다.

v12.16.1

다음 명령어를 실행하여 NPM 버전을 확인할 수도 있습니다.

npm --version

다음 출력에 NPM 버전이 표시되어야 합니다.

6.13.4

Node.js 애플리케이션 만들기

먼저 애플리케이션을 위한 디렉토리를 생성해야 합니다. 다음 명령을 실행하여 만들 수 있습니다.

mkdir nodeapp

다음으로 디렉토리를 nodeapp으로 변경하고 다음 명령을 사용하여 express를 설치합니다.

cd nodeapp
npm install express

다음으로 nano 편집기를 사용하여 express로 샘플 Node.js 애플리케이션을 만듭니다.

nano app.js

다음 내용을 추가합니다.

var express = require('express');
var app = express();
app.get('/', function(req, res){
   res.send("Nginx as Frontend Server for Node.js!");
});
app.listen(8000, '127.0.0.1');

완료되면 파일을 저장하고 닫습니다.

다음으로 다음 명령을 사용하여 애플리케이션을 실행합니다.

node app.js

그런 다음 다른 터미널을 열고 다음 명령으로 애플리케이션을 확인합니다.

netstat -antup | grep 8000

Node.js 애플리케이션이 포트 8000에서 수신 대기 중임을 확인해야 합니다.

tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN      26193/node

아래와 같이 curl 명령을 사용하여 애플리케이션을 확인할 수도 있습니다.

curl http://127.0.0.1:8000

모든 것이 정상이면 다음과 같은 결과가 표시됩니다.

Nginx as Frontend Server for Node.js!

PM2 설치 및 구성

PM2는 Node.js 애플리케이션을 관리하는 프로세스 관리자입니다. PM2를 사용하여 부팅 시 Node.js 애플리케이션을 쉽게 시작, 중지 및 활성화할 수 있습니다.

먼저 아래와 같이 NPM을 사용하여 최신 버전의 PM2를 설치합니다.

npm install pm2 -g

설치가 완료되면 다음 명령을 사용하여 디렉터리를 nodeapp 및 애플리케이션으로 변경합니다.

cd nodeapp
pm2 start app.js

애플리케이션이 시작되면 다음과 같은 결과가 표시되어야 합니다.

                        -------------

__/""""\____/"\____________/"\____/"""_____
 _\/"/////////"_\/""________/""__/"///////"___
  _\/"_______\/"_\/"//"____/"//"_\///______\//"__
   _\/""""\/__\/"\///"/"/_\/"___________/"/___
    _\/"/////////____\/"__\///"/___\/"________/"//_____
     _\/"_____________\/"____\///_____\/"_____/"//________
      _\/"_____________\/"_____________\/"___/"/___________
       _\/"_____________\/"_____________\/"__/"""""_
        _\///______________\///______________\///__\///////////////__


                          Runtime Edition

        PM2 is a Production Process Manager for Node.js applications
                     with a built-in Load Balancer.

                Start and Daemonize any application:
                $ pm2 start app.js

                Load Balance 4 instances of api.js:
                $ pm2 start api.js -i 4

                Monitor in production:
                $ pm2 monitor

                Make pm2 auto-boot at server restart:
                $ pm2 startup

                To go further checkout:
                http://pm2.io/


                        -------------

[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /root/nodeapp/app.js in fork_mode (1 instance)
[PM2] Done.
?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
? id  ? name   ? namespace   ? version ? mode    ? pid      ? uptime ? ?    ? status    ? cpu      ? mem      ? user     ? watching ?
?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
? 0   ? app    ? default     ? N/A     ? fork    ? 13202    ? 0s     ? 0    ? online    ? 0%       ? 27.2mb   ? root     ? disabled ?
?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

위 출력에서 애플리케이션 PID, 가동 시간, 상태, CPU 및 메모리 사용량과 같은 매우 유용한 정보를 볼 수 있습니다.

그런 다음 다음 명령을 실행하여 Node.js 애플리케이션이 부팅 시 자동으로 시작되도록 Node.js 애플리케이션용 시작 스크립트를 만들고 구성합니다.

pm2 startup

다음 출력이 표시되어야 합니다.

[PM2] Init System found: systemd
Platform systemd
Template
[Unit]
Description=PM2 process manager
Documentation=https://pm2.keymetrics.io/
After=network.target

[Service]
Type=forking
User=root
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
Environment=PM2_HOME=/root/.pm2
PIDFile=/root/.pm2/pm2.pid
Restart=on-failure

ExecStart=/usr/lib/node_modules/pm2/bin/pm2 resurrect
ExecReload=/usr/lib/node_modules/pm2/bin/pm2 reload all
ExecStop=/usr/lib/node_modules/pm2/bin/pm2 kill

[Install]
WantedBy=multi-user.target

Target path
/etc/systemd/system/pm2-root.service
Command list
[ 'systemctl enable pm2-root' ]
[PM2] Writing init configuration in /etc/systemd/system/pm2-root.service
[PM2] Making script booting at startup...
[PM2] [-] Executing: systemctl enable pm2-root...
Created symlink /etc/systemd/system/multi-user.target.wants/pm2-root.service → /etc/systemd/system/pm2-root.service.
[PM2] [v] Command successfully executed.
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save

[PM2] Remove init script via:
$ pm2 unstartup systemd

그런 다음 다음 명령을 사용하여 PM2 서비스를 시작합니다.

systemctl start pm2-root

다음으로 다음 명령을 사용하여 PM2 서비스의 상태를 확인합니다.

systemctl status pm2-root

다음 출력이 표시되어야 합니다.

? pm2-root.service - PM2 process manager
   Loaded: loaded (/etc/systemd/system/pm2-root.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2020-03-26 06:04:28 UTC; 2s ago
     Docs: https://pm2.keymetrics.io/
  Process: 13387 ExecStart=/usr/lib/node_modules/pm2/bin/pm2 resurrect (code=exited, status=0/SUCCESS)
 Main PID: 13191 (PM2 v4.2.3: God)
    Tasks: 0 (limit: 4915)
   CGroup: /system.slice/pm2-root.service
           ? 13191 PM2 v4.2.3: God Daemon (/root/.pm2)

Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: [PM2] Restoring processes located in /root/.pm2/dump.pm2.bak
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: [PM2][ERROR] Failed to read dump file in /root/.pm2/dump.pm2.bak
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: [PM2][ERROR] No processes saved; DUMP file doesn't exist
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: ? PM2+ activated | Instance Name: node.myserver.tld-109e | Dash: https://app.pm2.io/#/r/7p66twg
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: ????????????????????????????????????????????????????????????????????????????????????????????????
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: ? id  ? name   ? namespace   ? version ? mode    ? pid      ? uptime ? ?    ? status    ? cpu   
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: ????????????????????????????????????????????????????????????????????????????????????????????????
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: ? 0   ? app    ? default     ? N/A     ? fork    ? 13202    ? 8m     ? 0    ? online    ? 0%    
Mar 26 06:04:28 kolab.linuxbuz.com pm2[13387]: ????????????????????????????????????????????????????????????????????????????????????????????????
Mar 26 06:04:28 kolab.linuxbuz.com systemd[1]: Started PM2 process manager.

Nginx를 Node.js용 역방향 프록시로 구성

이 시점에서 Node.js 애플리케이션이 실행 중이고 localhost에서 수신 대기 중입니다. 다음으로 모든 사용자가 인터넷을 통해 애플리케이션에 액세스할 수 있도록 Nginx를 Node.js 애플리케이션의 프런트 엔드 프록시 서버로 구성해야 합니다.

먼저 다음 명령을 사용하여 Nginx 웹 서버를 설치합니다.

apt-get install nginx -y

설치가 완료되면 Node.js 애플리케이션용 Nginx 가상 호스트 구성 파일을 생성합니다.

nano /etc/nginx/sites-enabled/myapp.conf

다음 콘텐츠를 추가합니다.

server {
    listen 80;
    server_name node.myserver.tld;
    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
     }
}

완료되면 파일을 저장하고 닫습니다. 그런 다음 Nginx 서버를 다시 시작하여 변경 사항을 적용합니다.

systemctl restart nginx

다음 명령을 사용하여 Nginx 서비스의 상태를 확인할 수 있습니다.

systemctl status nginx

다음 출력이 표시되어야 합니다.

? nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2020-03-25 12:42:49 UTC; 5min ago
     Docs: man:nginx(8)
  Process: 26180 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 26182 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 26183 (nginx)
    Tasks: 3 (limit: 2359)
   Memory: 5.5M
   CGroup: /system.slice/nginx.service
           ??26183 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ??26184 nginx: worker process
           ??26185 nginx: worker process

Mar 25 12:42:49 debian10 systemd[1]: Starting A high performance web server and a reverse proxy server...
Mar 25 12:42:49 debian10 systemd[1]: Started A high performance web server and a reverse proxy server.

완료되면 다음 단계로 진행할 수 있습니다.

Node.js 애플리케이션에 액세스

이 시점에서 Nginx는 Node.js 애플리케이션을 제공하도록 구성됩니다.

이제 웹 브라우저를 열고 URL http://node.myserver.tld를 입력하십시오. 다음 화면에 Node.js 애플리케이션이 표시되어야 합니다.

결론

위의 기사에서는 Debian 10에서 Node.js 애플리케이션을 설정하는 방법을 배웠습니다. 또한 Node.js 애플리케이션을 데몬으로 실행하고 Nginx를 리버스 프록시로 구성하여 애플리케이션을 제공하는 방법도 배웠습니다. 이제 프로덕션 환경에서 Node.js 애플리케이션을 쉽게 호스팅할 수 있기를 바랍니다.