タイトル: 簡単なサーバー構築と起動方法
SEOタイトル: Node.js 最小サーバー構築 完全ガイド(http モジュール / Express / nodemon / ポート / トラブル対処)
| この記事の要点 |
|
はじめに
Node.js は JavaScript でサーバサイド処理を書ける実行環境です。標準モジュールの http だけで、ブラウザからアクセスできる最小限の Web サーバが組めるため、入門にぴったりの題材です。
事前準備
- Node.js(推奨は LTS バージョン)をインストール
- 動作確認: ターミナルで
node -v - 適当な作業フォルダを作って移動
# Node.js のバージョン確認
node -v
# v20.10.0 などが表示されればOK
# 作業フォルダ作成
mkdir my-server
cd my-server
最小サーバー(http モジュール)
作業フォルダ内に server.js を作成し、以下を貼り付けます。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.write('Node.js Server Start!');
res.end();
});
server.listen(8000, () => {
console.log('サーバー起動中... http://localhost:8000/');
});
起動
node server.js
# サーバー起動中... http://localhost:8000/
ブラウザで http://localhost:8000/ にアクセスすると Node.js Server Start! と表示されます。停止は Ctrl + C。
HTML を返す
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
My Server
こんにちは、Node.js
現在時刻: ${new Date().toLocaleString('ja-JP')}
`);
});
server.listen(8000);
JSON API を返す
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
message: 'Hello',
time: new Date().toISOString()
}));
});
server.listen(8000);
URL でルーティング
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const path = url.parse(req.url).pathname;
if (path === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('トップページ');
} else if (path === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Aboutページ');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('404 Not Found');
}
});
server.listen(8000);
Express を使うと簡単
本格的にルーティングやミドルウェアを使うなら Express が定番です。
# npm 初期化
npm init -y
# Express インストール
npm install express// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('トップページ');
});
app.get('/about', (req, res) => {
res.send('Aboutページ');
});
app.get('/api/users/:id', (req, res) => {
res.json({ id: req.params.id, name: 'Taro' });
});
app.listen(8000, () => {
console.log('Express server started: http://localhost:8000/');
});node app.js
nodemon — 自動再起動
ファイル保存時にサーバを自動再起動してくれる開発ツール。手動で node server.js を打ち直す必要がなくなります。
# グローバルインストール
npm install -g nodemon
# 起動(node の代わりに nodemon)
nodemon server.js
ポート番号の選び方
| 範囲 | 用途 |
|---|---|
| 0-1023 | well-known ports(管理者権限必要、80 / 443 等) |
| 1024-49151 | registered ports(一般用、開発に使いやすい) |
| 49152-65535 | dynamic / private ports(OS が動的に割当) |
開発では 3000 / 4000 / 5000 / 8000 / 8080 がよく使われます。本番で 80 / 443 を使うときはリバースプロキシ(nginx 等)の後ろに置くのが一般的です。
環境変数でポート切替
const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
console.log(`http://localhost:${PORT}/`);
});# Linux / macOS
PORT=4000 node server.js
# Windows (PowerShell)
$env:PORT = 4000; node server.js
よくあるトラブル
| 症状 | 原因 / 対処 |
|---|---|
| EADDRINUSE | ポートが他のプロセスで使用中。別ポートに変えるか、占有プロセスを終了 |
| EACCES | 1024 未満のポートに非 root で listen している。1024 以上に変更 |
| 文字化け | Content-Type に charset=utf-8 を付ける |
| Cannot find module 'express' | npm install express を実行 |
| 外部からつながらない | OS / クラウドのファイアウォール、0.0.0.0 へバインドの確認 |
外部公開する際のポイント
- 本番では Node を直接公開しない — nginx 等のリバースプロキシ越しが定番
- HTTPS は Let's Encrypt + リバースプロキシで終端
- プロセス管理には PM2、systemd、Docker 等
- 環境変数で秘匿情報を管理(dotenv が便利)
FAQ
Q: 何度実行しても同じ画面しか出ない
A: ブラウザのキャッシュです。Ctrl + F5 で強制リロードを試してください。
Q: ポートを変えるには?
A: server.listen(3000) のように数値を変えて再起動するか、上記の環境変数方式を使います。
Q: TypeScript で書きたい
A: ts-node や tsx を使うとビルドなしで実行できます。本格運用なら tsc で JS にコンパイル → node dist/server.js。
関連
- Node.js — サーバサイド JS ランタイム
- Express — 最も普及している Node 用 Web フレームワーク
- npm — Node のパッケージマネージャ
- nodemon — ファイル変更で自動再起動
- http モジュール — Node 標準の HTTP サーバ機能