Nginx 리버스 프록시로 Node.js 앱 연결하는 방법 (WebSocket 포함)

Ubuntu 26.04 서버에서 Node.js 앱을 Nginx 뒤에 두고 리버스 프록시로 연결하는 방법을 정리합니다. proxy_pass와 헤더 설정, WebSocket이 연결되지 않을 때 필요한 Upgrade 설정…

Ubuntu 26.04Nginx 1.28x86_64약 20분

검증된 문서입니다

클라우드 서버를 생성하여 이 문서의 명령을 처음부터 끝까지 그대로 실행하고 확인한 문서입니다.

운영체제
Ubuntu 26.04.1 LTS · x86_64
설치 버전
Nginx 1.28.3 (1.28.3-2ubuntu1.12), Node.js 24.22.1 (nvm 0.40.8), ws 8.22
테스트 서버
DigitalOcean · 1 vCPU / 2 GB RAM / 50 GB SSD (s-1vcpu-2gb, sgp1)
마지막 확인
2026-10-27

이 문서에는 제휴 링크가 포함되어 있습니다. 링크를 통해 가입하면 코드샌드가 일정 수수료를 받을 수 있으며, 문서 내용과 평가에는 영향을 주지 않습니다.

Ubuntu 26.04 서버에서 Node.js 앱을 Nginx 뒤에 두고 리버스 프록시로 연결하는 방법을 정리합니다. proxy_pass와 헤더 설정, WebSocket이 연결되지 않을 때 필요한 Upgrade 설정, 앱이 꺼졌을 때의 502 오류, systemd로 앱을 계속 실행하는 방법까지 다룹니다.

1. 준비물

서버가 없다면 DigitalOcean의 Droplet(1 vCPU · 2GB)을 생성해 보세요. 이 문서의 모든 과정은 Droplet(1 vCPU · 2GB 메모리 · 50GB SSD · Ubuntu 26.04 · 싱가포르)으로 서버를 생성하고, Nginx 1.28.3과 nvm으로 설치한 Node.js 24.22.1을 쓰는 일반 사용자 계정(devuser)으로 확인했습니다. 외부 접속은 다른 PC(예시 IP 203.0.113.10)에서 서버(예시 IP 203.0.113.20)로 확인했습니다.

2. 확인용 Node.js 앱 만들기

설치된 Node.js 버전을 확인합니다.

node -v
v24.22.1

앱 폴더를 만들고 package.json을 만듭니다. npm init -y의 출력(package.json 내용)은 생략했습니다.

mkdir ~/myapp && cd ~/myapp
npm init -y

WebSocket 서버를 만드는 ws 패키지를 설치합니다.

npm install ws
added 1 package, and audited 2 packages in 1s

found 0 vulnerabilities

HTTP 요청에는 받은 요청 헤더를 그대로 돌려주고, WebSocket으로 접속하면 connected를 보낸 뒤 받은 메시지 앞에 echo:를 붙여 돌려주는 앱입니다. 앱은 127.0.0.1:3000에서만 접속을 받기 때문에 외부에서는 Nginx를 거쳐야만 접속할 수 있습니다. 출력은 없습니다.

cat > ~/myapp/app.js <<'EOF'
const http = require('http');
const { WebSocketServer } = require('ws');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end(
    `Hello from Node.js ${process.version}\n` +
    `Host: ${req.headers.host}\n` +
    `X-Real-IP: ${req.headers['x-real-ip']}\n` +
    `X-Forwarded-For: ${req.headers['x-forwarded-for']}\n` +
    `X-Forwarded-Proto: ${req.headers['x-forwarded-proto']}\n`
  );
});

const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
  ws.send('connected');
  ws.on('message', (msg) => ws.send(`echo: ${msg}`));
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Listening on http://127.0.0.1:3000');
});
EOF

앱을 실행합니다. 이 터미널은 앱이 실행되는 동안 계속 열어 둡니다.

cd ~/myapp
node app.js
Listening on http://127.0.0.1:3000

새 터미널을 열어(SSH라면 한 번 더 접속해) 앱에 직접 요청해 봅니다. 프록시를 거치지 않았기 때문에 X-로 시작하는 헤더는 모두 undefined입니다.

curl http://127.0.0.1:3000
Hello from Node.js v24.22.1
Host: 127.0.0.1:3000
X-Real-IP: undefined
X-Forwarded-For: undefined
X-Forwarded-Proto: undefined

3000 포트는 서버 자신(127.0.0.1)에서만 열려 있습니다.

sudo ss -tlnp | grep 3000
LISTEN 0      511        127.0.0.1:3000      0.0.0.0:*    users:(("MainThread",pid=5890,fd=21))

WebSocket도 서버 안에서 확인합니다. Node.js 24에는 WebSocket 클라이언트가 기본으로 들어 있어서 따로 설치할 것이 없습니다.

node -e "const ws = new WebSocket('ws://127.0.0.1:3000'); ws.onmessage = (e) => { console.log(e.data); if (e.data === 'connected') ws.send('hello'); else ws.close(); };"
connected
echo: hello

3. Nginx 리버스 프록시 설정

먼저 HTTP만 넘기는 기본 설정으로 사이트 파일을 만듭니다. 출력은 없습니다.

sudo tee /etc/nginx/sites-available/myapp > /dev/null <<'EOF'
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF
  • proxy_pass: 받은 요청을 넘길 앱의 주소입니다.
  • Host: 브라우저가 요청한 도메인(또는 IP)을 앱에 그대로 전달합니다. 없으면 앱은 127.0.0.1:3000으로 받습니다.
  • X-Real-IP, X-Forwarded-For: 접속한 사람의 실제 IP입니다. 없으면 앱에는 모든 요청이 Nginx(127.0.0.1)에서 온 것으로 보입니다.
  • X-Forwarded-Proto: 브라우저가 http와 https 중 무엇으로 접속했는지 앱에 알려 줍니다.

사이트를 켜고 기본 사이트의 링크를 지웁니다. 두 사이트가 모두 default_server로 적혀 있으면 설정 확인에서 오류가 납니다.

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/ && sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
sudo systemctl reload nginx

PC(203.0.113.10)에서 서버 IP로 접속합니다. 앱이 받은 Host와 IP가 PC에서 보낸 값으로 바뀌었습니다.

curl http://203.0.113.20
Hello from Node.js v24.22.1
Host: 203.0.113.20
X-Real-IP: 203.0.113.10
X-Forwarded-For: 203.0.113.10
X-Forwarded-Proto: http

4. WebSocket 연결 설정

PC에서 WebSocket으로 접속해 봅니다. 이 PC에는 WebSocket 클라이언트가 없어서 Docker로 Node.js 이미지를 실행해 wscat을 썼습니다. -x hello는 접속하면 hello를 보낸다는 뜻이고, -w 1은 보낸 뒤 1초 동안 답을 기다렸다가 끝낸다는 뜻입니다. --rm 옵션을 붙였기 때문에 실행이 끝나면 컨테이너는 자동으로 삭제됩니다. npm 새 버전 안내 줄은 생략했습니다.

docker run --rm -t node:24-alpine npx -y wscat -c ws://203.0.113.20 -x hello -w 1
Unexpected server response: 200

WebSocket은 처음에 HTTP로 접속한 뒤 Upgrade: websocket 헤더로 연결 방식을 바꾸자고 요청합니다. 그런데 Nginx는 이 헤더를 앱에 넘기지 않기 때문에 앱은 일반 HTTP 요청으로 받아 200을 돌려주고, 클라이언트는 연결 방식이 바뀌었다는 응답(101)을 받지 못해 연결을 끝냅니다. Nginx 접속 로그에도 200으로 남습니다.

sudo tail -n 1 /var/log/nginx/access.log
203.0.113.10 - - [27/Oct/2026:08:40:50 +0000] "GET / HTTP/1.1" 200 143 "-" "-"

설정 파일에 WebSocket용 설정을 추가합니다. 출력은 없습니다.

sudo tee /etc/nginx/sites-available/myapp > /dev/null <<'EOF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
    }
}
EOF
  • map: 요청에 Upgrade 헤더가 있으면 Connection 값을 upgrade로, 없으면 close로 정합니다. 일반 HTTP 요청과 WebSocket 요청을 같은 location에서 함께 처리할 수 있습니다.
  • proxy_http_version 1.1: Nginx가 앱에 요청할 때 HTTP/1.1을 씁니다. 연결 방식 바꾸기(Upgrade)는 HTTP/1.1에 있는 기능입니다.
  • Upgrade, Connection: 브라우저가 보낸 WebSocket 전환 요청을 앱에 넘깁니다.
  • proxy_read_timeout 3600s: 앱에서 1시간 동안 아무것도 오지 않아야 연결을 끊습니다. 기본값은 60초이고, 그동안 앱에서 아무 데이터도 오지 않으면 Nginx가 연결을 끊습니다.
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
sudo systemctl reload nginx

PC에서 다시 접속하면 앱이 보낸 connected와 hello에 대한 답이 표시됩니다.

docker run --rm -t node:24-alpine npx -y wscat -c ws://203.0.113.20 -x hello -w 1
connected
echo: hello

접속 로그의 상태 코드가 101(연결 방식 전환)로 바뀌었습니다.

sudo tail -n 1 /var/log/nginx/access.log
203.0.113.10 - - [27/Oct/2026:08:41:10 +0000] "GET / HTTP/1.1" 101 26 "-" "-"

일반 HTTP 요청도 그대로 됩니다.

curl http://203.0.113.20
Hello from Node.js v24.22.1
Host: 203.0.113.20
X-Real-IP: 203.0.113.10
X-Forwarded-For: 203.0.113.10
X-Forwarded-Proto: http

5. 앱이 꺼졌을 때: 502 Bad Gateway

node app.js를 실행한 터미널에서 Ctrl+C를 눌러 앱을 끄고 PC에서 접속하면 502 오류가 표시됩니다. Nginx는 정상인데 요청을 넘길 앱이 없다는 뜻입니다.

curl -i http://203.0.113.20
HTTP/1.1 502 Bad Gateway
Server: nginx/1.28.3 (Ubuntu)
Date: Tue, 27 Oct 2026 08:41:26 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive

<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.28.3 (Ubuntu)</center>
</body>
</html>

Nginx 오류 로그에는 127.0.0.1:3000에 접속하지 못했다(111: Connection refused)고 남습니다.

sudo tail -n 1 /var/log/nginx/error.log
2026/10/27 08:41:26 [error] 7151#7151: *12 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.10, server: _, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "203.0.113.20"

터미널에서 실행한 앱은 터미널을 닫거나 서버를 재부팅하면 꺼집니다. 다음 단계처럼 systemd 서비스로 등록하면 앱이 항상 실행됩니다. 502의 다른 원인은 Nginx 502 Bad Gateway 해결 방법에 정리했습니다.

6. systemd로 앱 계속 실행하기

systemd 서비스 파일에는 node의 전체 경로를 적어야 합니다. nvm으로 설치한 Node.js는 사용자 폴더에 있고, systemd는 nvm 설정을 읽지 않기 때문입니다. 경로는 which node로 확인합니다.

which node
/home/devuser/.nvm/versions/node/v24.22.1/bin/node

서비스 파일을 만듭니다. User와 경로의 devuser는 자신의 사용자 이름으로 바꾸세요. Restart=on-failure는 앱이 오류로 꺼지면 다시 실행한다는 뜻입니다. 출력은 없습니다.

sudo tee /etc/systemd/system/myapp.service > /dev/null <<'EOF'
[Unit]
Description=myapp (Node.js)
After=network.target

[Service]
User=devuser
WorkingDirectory=/home/devuser/myapp
ExecStart=/home/devuser/.nvm/versions/node/v24.22.1/bin/node app.js
Restart=on-failure
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

systemd에 새 파일을 읽게 한 뒤, 서비스를 켜고 재부팅 때 자동으로 실행되게 합니다. enable --now는 이 두 가지를 한 번에 한다는 뜻입니다.

sudo systemctl daemon-reload
sudo systemctl enable --now myapp
Created symlink '/etc/systemd/system/multi-user.target.wants/myapp.service' → '/etc/systemd/system/myapp.service'.
systemctl status myapp --no-pager | head -4
● myapp.service - myapp (Node.js)
     Loaded: loaded (/etc/systemd/system/myapp.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-10-27 08:41:41 UTC; 959ms ago
 Invocation: 9185fc7b0eab4a63bea8654a295031f3
curl http://203.0.113.20
Hello from Node.js v24.22.1
Host: 203.0.113.20
X-Real-IP: 203.0.113.10
X-Forwarded-For: 203.0.113.10
X-Forwarded-Proto: http

앱이 갑자기 꺼졌을 때 다시 실행되는지 확인해 봅니다. kill -9로 앱 프로세스를 강제로 끝냅니다. $(systemctl show -p MainPID --value myapp)는 서비스의 프로세스 번호로 바뀝니다. 출력은 없습니다.

sudo kill -9 $(systemctl show -p MainPID --value myapp)

몇 초 뒤 상태를 보면 다시 실행되어 있습니다.

systemctl is-active myapp
active

앱의 출력(console.log)과 다시 실행된 기록은 journalctl로 볼 수 있습니다.

sudo journalctl -u myapp --no-pager -n 6
Oct 27 08:41:41 opendoc-nginx-10271716 node[7859]: Listening on http://127.0.0.1:3000
Oct 27 08:41:43 opendoc-nginx-10271716 systemd[1]: myapp.service: Main process exited, code=killed, status=9/KILL
Oct 27 08:41:43 opendoc-nginx-10271716 systemd[1]: myapp.service: Failed with result 'signal'.
Oct 27 08:41:44 opendoc-nginx-10271716 systemd[1]: myapp.service: Scheduled restart job, restart counter is at 1.
Oct 27 08:41:44 opendoc-nginx-10271716 systemd[1]: Started myapp.service - myapp (Node.js).
Oct 27 08:41:44 opendoc-nginx-10271716 node[7987]: Listening on http://127.0.0.1:3000

7. 문제 해결

Unexpected server response: 200

WebSocket 클라이언트가 연결 방식 전환 응답(101)을 기다렸는데 일반 응답(200)을 받았다는 뜻입니다. Nginx 설정에 proxy_http_version 1.1, proxy_set_header Upgrade $http_upgrade, proxy_set_header Connection $connection_upgrade가 있는지 확인하세요. 설정을 고친 뒤에는 sudo nginx -t와 sudo systemctl reload nginx를 실행해야 반영됩니다. 4단계에서 실제 메시지와 고친 뒤의 결과를 볼 수 있습니다.

connect() failed (111: Connection refused) while connecting to upstream

502 Bad Gateway 응답과 함께 error.log에 남는 문구입니다. proxy_pass에 적은 주소에서 접속을 받는 프로그램이 없다는 뜻입니다. 앱이 꺼져 있거나, 앱이 쓰는 포트와 proxy_pass의 포트가 다를 때 생깁니다. sudo ss -tlnp | grep 3000으로 앱이 그 포트에서 실행 중인지 확인하고, systemd로 실행했다면 sudo journalctl -u myapp --no-pager -n 20에서 앱이 꺼진 이유를 확인하세요.

curl: (28) Connection timed out after 5009 milliseconds

PC에서 http://203.0.113.20:3000처럼 앱 포트로 직접 접속했을 때 표시됩니다. 앱은 127.0.0.1에서만 접속을 받고, ufw도 3000 포트를 열지 않았기 때문에 PC에서 http://203.0.113.20:3000으로는 접속할 수 없습니다. 의도한 상태이므로 Nginx 주소(80 포트)로 접속하세요. --max-time 5는 5초까지만 기다린다는 뜻입니다.

curl --max-time 5 http://203.0.113.20:3000
curl: (28) Connection timed out after 5009 milliseconds

8. 삭제하기

서비스를 끄고 자동 실행을 해제합니다.

sudo systemctl disable --now myapp
Removed '/etc/systemd/system/multi-user.target.wants/myapp.service'.

서비스 파일을 지우고 systemd에 다시 읽게 합니다. 출력은 없습니다.

sudo rm /etc/systemd/system/myapp.service
sudo systemctl daemon-reload

Nginx 사이트 설정을 지우고 기본 사이트를 다시 켭니다.

sudo rm /etc/nginx/sites-enabled/myapp /etc/nginx/sites-available/myapp
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
sudo systemctl reload nginx

앱 폴더를 지웁니다. 출력은 없습니다. Node.js와 nvm까지 지우려면 nvm 문서의 삭제하기를 따라 하세요.

rm -rf ~/myapp
systemctl status myapp --no-pager
Unit myapp.service could not be found.

PC에서 접속하면 Nginx 기본 페이지가 표시됩니다.

curl -s http://203.0.113.20 | grep -o "<title>.*</title>"
<title>Welcome to nginx!</title>

직접 해 보기

서버가 없다면 아래 업체에서 몇 분이면 Ubuntu 서버를 만들 수 있습니다. 이 문서는 DigitalOcean 에서 검증했습니다.