웹사이트 검색

Systemd 및 Nginx를 사용하여 Node.js 애플리케이션을 배포하는 방법


소개

웹 애플리케이션을 Droplet에 배포할 때 개발에 사용되는 것과 동일한 종류의 설정을 사용하고 싶을 수도 있습니다. 즉, "ruby app.rb\ 또는 "node server.js\를 단말기. 간단하고 쉬우면서도 가시적인 로그를 제공합니다. "screen\ 또는 "tmux\ 또는 "nohup\을 사용하여 SSH 세션이 중단된 경우에도 계속 실행되도록 할 수 있습니다. 이것은 위험합니다. 서버가 충돌하고 아무도 서버를 다시 시작하지 않으면 어떻게 됩니까?

하나는 cgroups를 사용할 수 있으며 고급 데몬 시작은 모두 통합된 방식으로 액세스, 제어 및 미세 조정할 수 있습니다.

이 튜토리얼은 간단한 Node.js 애플리케이션을 사용하지만 전부는 아니더라도 대부분의 다른 애플리케이션(예: Ruby, Python 등)에도 적용할 수 있습니다. PHP 웹 애플리케이션의 경우 보다 전문화된 LEMP 스택을 대신 사용하는 것이 좋습니다.

Fedora와 Arch 모두에 대한 명령이 제공되며, 잘못된 구성 및/또는 혼란을 피하기 위해 어떤 것이 있는지 계속 살펴보십시오. 표시되지 않은 경우 명령은 두 시스템에서 동일합니다. 또한 단계별로 시도하기 전에 전체 자습서를 읽어 내용이 무엇인지, 상황에 적합한지 파악하는 것이 좋습니다.

시스템 예비

  • systemd가 있는 서버. Arch Linux 및 Fedora 드롭릿은 기본적으로 이렇게 구성됩니다.
  • 리버스 프록시 http 및 websocket 서버로 사용되는 Nginx.\n
  • Git - nvm을 설치하고 git을 사용하는 경우 애플리케이션을 가져옵니다.\n
  • 루트 액세스. 일반 사용자로 로그인하여 모든 명령을 sudo하거나 su 또는 sudo su를 루트 프롬프트로 로그인할 수도 있습니다.\n

패키지 설치

아치:

# pacman -Sy
# pacman -S nginx git

페도라:

# yum install nginx git

신청 예비

원하는 대로 사용자 정의할 수 있는 설정이지만 시작하기 전에 결정하고 설정해야 합니다.

사용자

응용 프로그램은 별도의 사용자 계정으로 실행됩니다. 이름을 선택하십시오. 이름은 쉽게 기억하고 유지 관리할 수 있도록 응용 프로그램과 관련되어야 합니다. 여기서는 srv-node-sample이 사용됩니다.

# useradd -mrU srv-node-sample

포트

충돌을 피하려면 높은 포트를 선택하십시오. 여기서는 "15301\을 사용합니다.

애플리케이션 설정

응용 프로그램을 실행하는 데 필요한 것을 설치하여 시작하십시오. Node.js(및 Ruby, Python…)의 경우 시스템의 런타임을 사용하거나 사용자별 설치(예: virtualenv 사용 등)의 두 가지 선택이 있습니다.

시스템 노드 사용

아치:

# pacman -S nodejs

페도라:

# yum install nodejs

사용자별 설치 사용

이는 애플리케이션의 홈 디렉터리(예: /home/srv-node-sample)에 설치해야 하며 해당 사용자로 로그인하여 가장 쉽게 수행할 수 있습니다.

# su srv-node-sample
$ cd
$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh
$ source ~/.nvm/nvm.sh
$ nvm install 0.10
$ nvm alias default 0.10

그런 다음 노드 바이너리가 설치된 위치를 기록해 둡니다.

$ which node
/home/srv-node-sample/.nvm/v0.10.22/bin/node

애플리케이션 배포

srv-node-sample에 로그인한 상태에서 코드를 배포합니다. 이는 예시일 뿐이며 프로세스는 다를 수 있습니다.

$ git clone git@server.company.tld:user/repo.git .
$ npm install
$ grunt deploy

이 자습서에서는 다음 샘플 애플리케이션이 사용됩니다.

js
var http = require('http');
http.createServer(function(req, res) {
    res.end('<h1>Hello, world.</h1>');
}).listen(15301);

그런 다음 루트로 돌아갑니다.

$ exit

Nginx 설정

이 튜토리얼은 필요한 구성에 대해서만 간략하게 설명합니다. Nginx 구성에 대한 자세한 튜토리얼은 nginx 매뉴얼을 참조하세요.

이것을 서버 블록에 배치하십시오.

location / {
    proxy_pass http://localhost:15301/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

그런 다음 데몬을 설정합니다.

# systemctl enable nginx
# systemctl restart nginx

체계적인 설정

/etc/systemd/system/node-sample.service에서 애플리케이션에 대한 서비스 파일을 생성합니다.

채워야 할 몇 가지 변수가 있습니다.

  • [node binary] 이것은 srv-node-sample 사용자로서 \which node의 출력입니다. /usr/bin/node 또는 ~/.nvm/... 경로는 위에서 언급했습니다.\n
  • [메인 파일] 애플리케이션의 메인 파일입니다. 여기서는 'index.js\'입니다.
  • srv-node-sample을 바꾸는 것을 잊지 마세요!

[Service]
ExecStart=[node binary] /home/srv-node-sample/[main file]
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=node-sample
User=srv-node-sample
Group=srv-node-sample
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

이제 서비스를 시작합니다.

# systemctl enable node-sample
# systemctl start node-sample

용법

상태

# systemctl status node-sample
node-sample.service
   Loaded: loaded (/etc/systemd/system/node-sample.service; enabled)
   Active: active (running) since Fri 2013-11-22 01:12:15 UTC; 35s ago
 Main PID: 7213 (node)
   CGroup: name=systemd:/system/node-sample.service
           └─7213 /home/srv-node-sample/.nvm/v0.10.22/bin/node /home/srv-nod...

Nov 22 01:12:15 d02 systemd[1]: Started node-sample.service.

로그

# journalctl -u node-sample
-- Logs begin at Thu 2013-11-21 19:05:17 UTC, end at Fri 2013-11-22 01:12:15 UTC. --
Nov 22 01:12:15 d02 systemd[1]: Starting node-sample.service...
Nov 22 01:12:15 d02 systemd[1]: Started node-sample.service.
Nov 22 01:12:30 d02 node-sample[7213]: Sample message from application

다시 시작, 중지 등

강제로 재시작:

# systemctl restart node-sample

애플리케이션을 중지합니다.

# systemctl stop node-sample

응용 프로그램이 죽거나 죽으면 자동으로 다시 시작됩니다.

# systemctl status node-sample
node-sample.service
   Loaded: loaded (/etc/systemd/system/node-sample.service; enabled)
   Active: active (running) since Fri 2013-11-22 01:12:15 UTC; 35s ago
 Main PID: 7213 (node)
   CGroup: name=systemd:/system/node-sample.service
           └─7213 /home/srv-node-sample/.nvm/v0.10.22/bin/node /home/srv-nod...

Nov 22 01:12:15 d02 systemd[1]: Started node-sample.service.

# kill 7213

# systemctl status node-sample
node-sample.service
   Loaded: loaded (/etc/systemd/system/node-sample.service; enabled)
   Active: active (running) since Fri 2013-11-22 01:54:37 UTC; 6s ago
 Main PID: 7236 (node)
   CGroup: name=systemd:/system/node-sample.service
           └─7236 /home/srv-node-sample/.nvm/v0.10.22/bin/node /home/srv-nod...

Nov 22 01:54:37 d02 systemd[1]: node-sample.service holdoff time over, sch...t.
Nov 22 01:54:37 d02 systemd[1]: Stopping node-sample.service...
Nov 22 01:54:37 d02 systemd[1]: Starting node-sample.service...
Nov 22 01:54:37 d02 systemd[1]: Started node-sample.service.

PID가 변경되어 응용 프로그램이 실제로 종료되고 다시 시작되었음을 나타냅니다.

웹소켓

애플리케이션이 웹 소켓을 사용하는 경우 Nginx 구성에 다음 행을 추가해야 합니다.

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;

Nginx를 다시 로드해야 합니다.

# systemctl reload nginx

제출자: Félix Saparelli