0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nginx から、Node.js のサーバーにリバースプロキシーで接続

0
Posted at

Node.js のプログラム

/usr/local/server/server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });

  res.end('hello world.\n');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

動作確認

Node.js サーバーの起動

$ node server.js 
Server running on port 3000

curl で接続

$ curl http://localhost:3000
hello world.

Httpie で接続

http http://localhost:3000

Systemd で起動する

設定ファイル

/etc/systemd/system/node-hello.service
[Unit]
Description=Node Hello Server
After=network.target

[Service]
ExecStart=/usr/local/bin/node /usr/local/server/server.js
Restart=always
User=www-data
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

起動

sudo systemctl start node-hello

確認

$ sudo systemctl status node-hello
● node-hello.service - Node Hello Server
     Loaded: loaded (/etc/systemd/system/node-hello.service; disabled; preset: >
     Active: active (running) since Fri 2026-05-22 15:37:39 JST; 25s ago

Nginx の設定

/etc/nginx/sites-available/default
(省略)
location /node { 
        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;
    }

(省略)

Nginx の設定ファイルの確認

sudo nginx -t

再起動

sudo systemctl restart nginx

接続確認

Curl

$ curl http://localhost/node
hello world.

Httpie

$ http http://localhost/node
HTTP/1.1 200 OK
Connection: keep-alive
Content-Type: text/plain; charset=UTF-8
Date: Fri, 22 May 2026 06:42:41 GMT
Server: nginx/1.28.3 (Ubuntu)
Transfer-Encoding: chunked

hello world.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?