この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:3
ページ更新者:T
更新日時:2026-06-11 07:07:02

タイトル: 簡単なサーバー構築と起動方法
SEOタイトル: Node.js 最小サーバー構築 完全ガイド(http モジュール / Express / nodemon / ポート / トラブル対処)

この本文には実行可能なタグ等が含まれるため、安全のためHTMLソースとして表示しています。本文データは変更していません。

<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;background:#fffbea;border:1px solid #f4c430;margin:1em 0;width:100%"><tr><td style="background:#f4c430;color:#000;font-weight:bold;padding:8px">この記事の要点</td></tr><tr><td style="padding:10px"><ul><li>Node.js は標準モジュール <code>http</code> だけで<strong>数行で HTTP サーバが書ける</strong></li><li><strong>server.js</strong> に <code>http.createServer().listen(port)</code> を書き、<code>node server.js</code> で起動</li><li>リクエストハンドラ <code>(req, res) => { ... }</code> でレスポンスを組み立て、<code>res.end()</code> で送信</li><li>本格的には <strong>Express</strong> 等のフレームワークを使うのが定番(ルーティング / ミドルウェア / エラー処理)</li><li>開発時は <strong>nodemon</strong> でファイル保存時に自動再起動できると効率的</li></ul></td></tr></table>
<h2>はじめに</h2>

<p><strong>Node.js</strong> は JavaScript でサーバサイド処理を書ける実行環境です。標準モジュールの <code>http</code> だけで、ブラウザからアクセスできる最小限の Web サーバが組めるため、入門にぴったりの題材です。</p>

<h2>事前準備</h2>

<ol>
<li>Node.js(推奨は LTS バージョン)をインストール</li>
<li>動作確認: ターミナルで <code>node -v</code></li>
<li>適当な作業フォルダを作って移動</li>
</ol>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-bash"># Node.js のバージョン確認
node -v
# v20.10.0 などが表示されればOK

# 作業フォルダ作成
mkdir my-server
cd my-server</code></pre>
<h2>最小サーバー(http モジュール)</h2>

<p>作業フォルダ内に <strong>server.js</strong> を作成し、以下を貼り付けます。</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-javascript">const http = require(&apos;http&apos;);

const server = http.createServer((req, res) => {
    res.writeHead(200, { &apos;Content-Type&apos;: &apos;text/plain; charset=utf-8&apos; });
    res.write(&apos;Node.js Server Start!&apos;);
    res.end();
});

server.listen(8000, () => {
    console.log(&apos;サーバー起動中... http://localhost:8000/&apos;);
});</code></pre>
<h2>起動</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-bash">node server.js
# サーバー起動中... http://localhost:8000/</code></pre>
<p>ブラウザで <strong>http://localhost:8000/</strong> にアクセスすると <code>Node.js Server Start!</code> と表示されます。停止は <strong>Ctrl + C</strong>。</p>

<h2>HTML を返す</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-javascript">const http = require(&apos;http&apos;);

const server = http.createServer((req, res) => {
    res.writeHead(200, { &apos;Content-Type&apos;: &apos;text/html; charset=utf-8&apos; });
    res.end(`
        <!DOCTYPE html>
        <html lang="ja">
        <head><meta charset="UTF-8"><title>My Server</title></head>
        <body>
            <h1>こんにちは、Node.js</h1>
            <p>現在時刻: ${new Date().toLocaleString(&apos;ja-JP&apos;)}</p>
        </body>
        </html>
    `);
});

server.listen(8000);</code></pre>
<h2>JSON API を返す</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-javascript">const http = require(&apos;http&apos;);

const server = http.createServer((req, res) => {
    res.writeHead(200, { &apos;Content-Type&apos;: &apos;application/json; charset=utf-8&apos; });
    res.end(JSON.stringify({
        message: &apos;Hello&apos;,
        time: new Date().toISOString()
    }));
});

server.listen(8000);</code></pre>
<h2>URL でルーティング</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-javascript">const http = require(&apos;http&apos;);
const url = require(&apos;url&apos;);

const server = http.createServer((req, res) => {
    const path = url.parse(req.url).pathname;

    if (path === &apos;/&apos;) {
        res.writeHead(200, { &apos;Content-Type&apos;: &apos;text/plain; charset=utf-8&apos; });
        res.end(&apos;トップページ&apos;);
    } else if (path === &apos;/about&apos;) {
        res.writeHead(200, { &apos;Content-Type&apos;: &apos;text/plain; charset=utf-8&apos; });
        res.end(&apos;Aboutページ&apos;);
    } else {
        res.writeHead(404, { &apos;Content-Type&apos;: &apos;text/plain; charset=utf-8&apos; });
        res.end(&apos;404 Not Found&apos;);
    }
});

server.listen(8000);</code></pre>
<h2>Express を使うと簡単</h2>

<p>本格的にルーティングやミドルウェアを使うなら <strong>Express</strong> が定番です。</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-bash"># npm 初期化
npm init -y

# Express インストール
npm install express</code></pre><pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-javascript">// app.js
const express = require(&apos;express&apos;);
const app = express();

app.get(&apos;/&apos;, (req, res) => {
    res.send(&apos;トップページ&apos;);
});

app.get(&apos;/about&apos;, (req, res) => {
    res.send(&apos;Aboutページ&apos;);
});

app.get(&apos;/api/users/:id&apos;, (req, res) => {
    res.json({ id: req.params.id, name: &apos;Taro&apos; });
});

app.listen(8000, () => {
    console.log(&apos;Express server started: http://localhost:8000/&apos;);
});</code></pre><pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-bash">node app.js</code></pre>
<h2>nodemon &mdash; 自動再起動</h2>

<p>ファイル保存時にサーバを自動再起動してくれる開発ツール。手動で <code>node server.js</code> を打ち直す必要がなくなります。</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-bash"># グローバルインストール
npm install -g nodemon

# 起動(node の代わりに nodemon)
nodemon server.js</code></pre>
<h2>ポート番号の選び方</h2>

<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;width:100%">
<thead><tr style="background:#e3f2fd"><th>範囲</th><th>用途</th></tr></thead>
<tbody>
<tr><td>0-1023</td><td>well-known ports(管理者権限必要、80 / 443 等)</td></tr>
<tr><td>1024-49151</td><td>registered ports(一般用、開発に使いやすい)</td></tr>
<tr><td>49152-65535</td><td>dynamic / private ports(OS が動的に割当)</td></tr>
</tbody>
</table>

<p>開発では <strong>3000 / 4000 / 5000 / 8000 / 8080</strong> がよく使われます。本番で 80 / 443 を使うときはリバースプロキシ(nginx 等)の後ろに置くのが一般的です。</p>

<h2>環境変数でポート切替</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-javascript">const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
    console.log(`http://localhost:${PORT}/`);
});</code></pre><pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-bash"># Linux / macOS
PORT=4000 node server.js

# Windows (PowerShell)
$env:PORT = 4000; node server.js</code></pre>
<h2>よくあるトラブル</h2>

<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;width:100%">
<thead><tr style="background:#e3f2fd"><th>症状</th><th>原因 / 対処</th></tr></thead>
<tbody>
<tr><td>EADDRINUSE</td><td>ポートが他のプロセスで使用中。別ポートに変えるか、占有プロセスを終了</td></tr>
<tr><td>EACCES</td><td>1024 未満のポートに非 root で listen している。1024 以上に変更</td></tr>
<tr><td>文字化け</td><td>Content-Type に <code>charset=utf-8</code> を付ける</td></tr>
<tr><td>Cannot find module 'express'</td><td><code>npm install express</code> を実行</td></tr>
<tr><td>外部からつながらない</td><td>OS / クラウドのファイアウォール、<code>0.0.0.0</code> へバインドの確認</td></tr>
</tbody>
</table>

<h2>外部公開する際のポイント</h2>

<ul>
<li><strong>本番では Node を直接公開しない</strong> &mdash; nginx 等のリバースプロキシ越しが定番</li>
<li><strong>HTTPS は Let's Encrypt</strong> + リバースプロキシで終端</li>
<li><strong>プロセス管理</strong>には PM2、systemd、Docker 等</li>
<li><strong>環境変数で秘匿情報</strong>を管理(dotenv が便利)</li>
</ul>

<h2>FAQ</h2>

<p><strong>Q: 何度実行しても同じ画面しか出ない</strong><br />
A: ブラウザのキャッシュです。<strong>Ctrl + F5</strong> で強制リロードを試してください。</p>

<p><strong>Q: ポートを変えるには?</strong><br />
A: <code>server.listen(3000)</code> のように数値を変えて再起動するか、上記の環境変数方式を使います。</p>

<p><strong>Q: TypeScript で書きたい</strong><br />
A: <code>ts-node</code> や <code>tsx</code> を使うとビルドなしで実行できます。本格運用なら <code>tsc</code> で JS にコンパイル → <code>node dist/server.js</code>。</p>

<h2>関連</h2>

<ul>
<li>Node.js — サーバサイド JS ランタイム</li>
<li>Express — 最も普及している Node 用 Web フレームワーク</li>
<li>npm — Node のパッケージマネージャ</li>
<li>nodemon — ファイル変更で自動再起動</li>
<li>http モジュール — Node 標準の HTTP サーバ機能</li>
</ul>