Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 208. IIS + Node.js 환경 구성 [링크 복사], [링크+제목 복사],
조회: 36131
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

IIS + Node.js 환경 구성

node.js의 node 프로세스가 현실적인 서비스를 하기 위해서는 80 포트를 사용해야 합니다. 그런데, 단순히 node.js 하나 운영하려고 웹 서버의 상징인 80 포트를 점유하는 것은 그리 바람직한 것은 아닙니다. 그래서 Apache 웹 서버의 경우 이를 위해 mod_proxy 등의 모듈을 이용해 proxy를 경유하는 형태로 처리하게 됩니다.

How to use Node.js with Apache on port 80
; http://www.chrisshiplet.com/2013/how-to-use-node-js-with-apache-on-port-80/

그렇다면 IIS라면 어떻게 해야 할까요? ^^




사실 처음에 제가 IIS + node.js 방법을 생각했을 때 누군가 80 포트를 공유하는 방식으로 node.exe를 확장한 프로그램을 공개하지 않았을까 기대했었습니다.

IIS의 80 포트를 공유하는 응용 프로그램 만드는 방법
; https://www.sysnet.pe.kr/2/0/1555

그런데, github에 공개되어 있는 확장 도구는 IIS의 module을 C/C++로 만드는 것으로 해결을 했습니다. (보시면 알겠지만, 이게 더 매끄럽게 통합이 됩니다.)

Hosting node.js applications in IIS on Windows
; https://github.com/tjanczuk/iisnode

자... 그럼 80 포트를 node.js와 ASP.NET이 사이좋게 사용하는 시나리오를 한번 실습해 볼까요? ^^

우선 "Hosting node.js applications in IIS on Windows" 글에 따라 다음과 같은 환경을 구성해 줍니다.

  1. 운영체제: Windows Vista 이후, 또는 Windows Server 2008 이후
  2. IIS 및 관리도구를 설치하고 ASP.NET을 활성화
  3. WebSocket은 Windows 8/2012 이상의 운영체제에서만 가능
  4. URL rewrite 모듈
  5. 윈도우 용 node.js

1, 2번은 ASP.NET 개발자라면 당연히 기본 셋팅되어 있을테니 생략하고, 3번은 WebSocket 기능을 사용하려면 IIS 8 이상이어야 한다고 명시한 것입니다. 왜냐하면 WebSocket이 IIS 8에 기본 내장되어 있기 때문에 그것을 쓰려는 것이고 2중으로 확장할 필요가 없어 그런 것 같습니다. URL Rewrite은 다음의 사이트에서 다운로드 받아 해결할 수 있습니다.

URL Rewrite
; http://www.iis.net/downloads/microsoft/url-rewrite

마지막으로 node.js는 MSI로 묶어 배포하는 버전을 설치해 주면 됩니다.

Latest node.js build for Windows (x86)
; http://go.microsoft.com/?linkid=9784334

설치는 msi만 실행해 주면 완료됩니다. 이후 cmd.exe 창을 열고 node를 실행하면 다음과 같이 실습할 수 있습니다. ^^

C:\Users\tester>node
> var test = 'test'
undefined
> console.log(test)
test
undefined
>

그나저나 윈도우에서 node.js 사용하는 방법이 많이 쉬워졌군요. ^^ 단순하게 msi만 실행해 주면 끝이라니.




이제 본격적으로 node.js와 IIS를 iisnode를 이용해 통합해 볼까요? ^^

iisnode for IIS 7.x/8.x: x86
; http://go.microsoft.com/?linkid=9784330

iisnode for IIS 7.x/8.x: x64
; http://go.microsoft.com/?linkid=9784331

위의 경로에서 플랫폼에 맞는 MSI 파일을 내려받아 설치해 줍니다. 역시 설치 과정은 단순하게 끝납니다.

자, 이제 ^^ node를 IIS의 웹 애플리케이션(또는 웹 사이트)에 통합할 수 있습니다. 적당하게 폴더를 하나 정해서 웹 애플리케이션을 하나 만들어 주고,

iis8_node_js_1.png

여기에서 node.js를 처리할 수 있도록 handler를 web.config을 이용해 연결해 주면 됩니다.

<configuration>
  <system.webServer>
    <handlers>
      <add name="iisnode" path="*.js" verb="*" modules="iisnode" />

      <!-- 
        또는 파일명까지 지정하는 것도 가능하고
      <add name="iisnode" path="hello.js" verb="*" modules="iisnode" />
      -->
    </handlers>    
  </system.webServer>
</configuration>

이것으로 통합이 완료되었습니다. ^^ 이제 c:\nodetest 폴더에 다음과 같은 내용의 hello.js 파일을 만들어 실습할 수 있습니다.

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, world! [helloworld sample]');
}).listen(process.env.PORT);  

테스트 삼아서 "http://localhost/NodeTest/hello.js"로 방문하면 hello.js의 실행 결과를 볼 수 있습니다. 물론 해당 웹 애플리케이션은 IIS의 여느 가상 애플리케이션과 다를 바가 없기 때문에 다음과 같이 test.aspx 파일도 c:\nodetest 폴더에 포함시킬 수 있고,

<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>

<%
string text = Request.QueryString["inputValue"];
double result = 0;

if (string.IsNullOrEmpty(text) == false)
{
    int number = Int32.Parse(text);
    result = Math.Sqrt(number);
}
%>

<head>
    <title>제곱근 구하는 예제</title>
</head>

<body>

<form method="get" action="sqrt.aspx">
숫자: <input type="text" name="inputValue" /><br /><br />
<input type="submit" value="전송" /><br />
</form><br />

<%
if (result != 0)
{
%>
제곱근: <%=result%>
<%
}
%>

</body>
</html>

이렇게 동일한 /NodeTest URL로 호출하는 것이 가능합니다.

  • http://localhost/NodeTest/test.aspx
  • http://localhost/NodeTest/hello.js

iis8_node_js_2.png

오~~~ 멋지지 않나요? ^^ Apache와 비교해서 훨씬 자연스럽게 통합되었습니다. (혹시 이 글에서 소개된 Apache + node.js보다 더 쉬운 방법을 알고 계신 분은 공유 부탁드립니다.)




오류 정리입니다.

hello.js를 방문했을 때 웹 브라우저에서 다음과 같은 오류 메시지를 보게 된다면?

The iisnode module is unable to start the node.exe process. Make sure the node.exe executable is available at the location specified in the system.webServer/iisnode/@nodeProcessCommandLine element of web.config. By default node.exe is expected in one of the directories listed in the PATH environment variable.


이는 x64에서 실습한 경우에 발생하는데 다음의 Q&A에서 자세하게 설명해 주고 있습니다.

Error running node app in WebMatrix
; http://stackoverflow.com/questions/13079199/error-running-node-app-in-webmatrix

"Hosting node.js applications in IIS on Windows" 글에 공개된 "Latest node.js build for Windows" 버전은 x86으로 곧장 링크되어 있습니다. 따라서, IIS x64 웹 애플리케이션에서 x86 버전의 "C:\Program Files (x86)\nodejs\node.exe" 경로를 찾아들어갈 수 없어 발생하는 것입니다. 웹 브라우저에서 보여주는 오류 메시지의 내용이 그것이며 따라서 다음과 같은 설정을 web.config에 추가해 주면 해결됩니다.

<configuration>
  <system.webServer>
    <handlers>
      <add name="iisnode" path="*.js" verb="*" modules="iisnode" />
    </handlers>    

    <iisnode watchedFiles="*.js;node_modules\*;routes\*.js;views\*.jade" 
             nodeProcessCommandLine="C:\Program Files (x86)\nodejs\node.exe"/>
  </system.webServer>
</configuration>

또는 x64 버전의 node를 설치해 주어도 됩니다. 이 버전은 현재 다음의 사이트에서 배포되고 있습니다.

Node v0.8.22 (Stable)
; http://blog.nodejs.org/2013/03/06/node-v0-8-22-stable/

Windows x64 Installer
; http://nodejs.org/dist/v0.8.22/x64/node-v0.8.22-x64.msi

주의할 것은 현재 만들어진 node.js MSI 설치 파일은 x64를 설치한 경우 x86으로 설치된 node가 자동으로 삭제된다는 점입니다. (굳이 이렇게 설치 파일을 만든 이유를 모르겠군요.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/30/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2015-08-02 04시39분
[질문자] node.js는 혼자 언어와 서버 역할을 다 할 수 있는데
굳이 IIS 서버를 쓰는 이유가 무엇인가요?
현재 웹앱을 IIS서버에 DB와 같이 올리고 서버 언어는 node.js를 쓸려고 해서 공부중입니다.
[guest]
2015-08-02 12시17분
Java에서 WAS를 쓰는 것과 같은 이치입니다. 호스팅 프로세스에 대한 관리를 IIS에 맡겨 Recycle 기능을 덤으로 얻을 수 있다면, 당연히 윈도우 환경에서 마다할 이유가 없을 것입니다. ^^
정성태
2015-09-01 02시51분
[질문자] 핸들러 부분 저건 어디서 수정할 수 있나요?
web.config 파일을 못찾겠어요 ㅠㅠ
[guest]
2015-09-01 03시11분
web.config 파일은 그냥 만들어 주면 됩니다. 위의 글에서라면 "c:\nodetest" 폴더에 새 파일로 생성하면 됩니다.
정성태
2015-09-02 03시09분
[질문자] iisnode encountered an error when processing the request.

HRESULT: 0x2
HTTP status: 500
HTTP reason: Internal Server Error
You are receiving this HTTP 200 response because system.webServer/iisnode/@devErrorsEnabled configuration setting is 'true'.

In addition to the log of stdout and stderr of the node.exe process, consider using debugging and ETW traces to further diagnose the problem.

The node.exe process has not written any information to stderr or iisnode was unable to capture this information. Frequent reason is that the iisnode module is unable to create a log file to capture stdout and stderr output from node.exe. Please check that the identity of the IIS application pool running the node.js application has read and write access permissions to the directory on the server where the node.js application is located. Alternatively you can disable logging by setting system.webServer/iisnode/@loggingEnabled element of web.config to 'false'.

이런 오류가 뜨는데 제가 완전 잘못한건가요?
xml configuration file을 web이라는 이름으로 만들어서 하니 저런 오류가 뜨네요...
기본서버파일인 wwwroot폴더에다 하는중인데 다 잘못됀건가요? 제가 iis는 초짜라서ㅠ
[guest]
2015-09-02 03시22분
이 글의 내용대로 실습했는데 그런 오류가 발생한다는 건가요?
정성태
2015-09-02 03시58분
[질문자] 네 그래서 찾아보니
IIS_IUSRS 그룹 쓰기 권한
이거랑 무슨 관련이 있는 것 같은데 한번 맨땅에 헤딩해보겠습니다!!
[guest]
2015-10-13 02시12분
정성태

1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13561정성태2/20/20242052닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242086디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242944오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242173닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241921Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241966Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242116닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241861VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241943닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241896닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242089닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242206Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242504개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242335개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242085개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241946Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241859닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241883오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241881Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241913오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241973VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242078Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242365개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242418닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242507닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242595닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...