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.