MeWrite Docs

Network: Connection refused

サーバーが接続を拒否した場合のエラー

概要

サーバーへの接続を試みたが、サーバー側が接続を拒否した場合に発生するエラーです。サービスが起動していない、ポートがリッスンされていない場合に発生します。

エラーメッセージ

Error: connect ECONNREFUSED 127.0.0.1:3000

または

curl: (7) Failed to connect to localhost port 3000: Connection refused

原因

  1. サービス未起動: アプリケーションが起動していない
  2. ポートの不一致: 異なるポートでリッスンしている
  3. バインドアドレス: localhost のみバインドしている
  4. ファイアウォール: ポートが閉じられている

解決策

1. サービスの起動確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# プロセス確認
ps aux | grep node
ps aux | grep python

# systemd サービス確認
sudo systemctl status myservice

# Docker コンテナ確認
docker ps
docker logs container_name

2. ポートの確認

1
2
3
4
5
6
7
8
9
# リッスンポート確認(Linux)
sudo netstat -tlnp | grep 3000
sudo ss -tlnp | grep 3000

# リッスンポート確認(macOS)
lsof -i :3000

# 使用中のポート一覧
sudo lsof -i -P -n | grep LISTEN

3. バインドアドレスの確認

1
2
3
4
5
6
7
8
// Node.js
// 悪い例:localhostのみ
app.listen(3000, 'localhost');

// 良い例:すべてのインターフェース
app.listen(3000, '0.0.0.0', () => {
  console.log('Server listening on port 3000');
});
1
2
3
4
5
6
# Python Flask
# 悪い例
app.run(port=3000)

# 良い例:すべてのインターフェース
app.run(host='0.0.0.0', port=3000)

4. Docker での接続

1
2
3
4
5
6
7
8
9
# docker-compose.yml
services:
  app:
    ports:
      - "3000:3000"  # ホスト:コンテナ

  db:
    expose:
      - "5432"  # コンテナ間通信のみ
1
2
3
# コンテナ内からの接続
# localhost ではなくサービス名を使用
docker exec -it app curl http://db:5432

5. ファイアウォールの設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Ubuntu (UFW)
sudo ufw allow 3000/tcp
sudo ufw status

# CentOS/RHEL (firewalld)
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload

# AWS Security Group
aws ec2 authorize-security-group-ingress \
  --group-id sg-xxxx \
  --protocol tcp \
  --port 3000 \
  --cidr 0.0.0.0/0

6. 待機とリトライ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// サービス起動を待機
async function waitForService(url, maxRetries = 30, delay = 1000) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      await axios.get(url, { timeout: 1000 });
      return true;
    } catch (error) {
      if (error.code !== 'ECONNREFUSED') throw error;
      console.log(`Waiting for service... (${i + 1}/${maxRetries})`);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  throw new Error('Service did not become available');
}

7. ヘルスチェックエンドポイント

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Express
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'healthy' });
});

// 起動時のDB接続確認
async function healthCheck() {
  try {
    await db.query('SELECT 1');
    return { db: 'connected' };
  } catch (error) {
    return { db: 'disconnected', error: error.message };
  }
}

8. Docker Compose の依存関係

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
services:
  app:
    depends_on:
      db:
        condition: service_healthy

  db:
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

9. Kubernetes での確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Pod の状態確認
kubectl get pods
kubectl describe pod myapp-xxx

# サービスの確認
kubectl get svc
kubectl describe svc myservice

# ポートフォワーディング
kubectl port-forward pod/myapp-xxx 3000:3000

10. ローカル開発での確認

1
2
3
4
5
6
7
8
# プロセスを強制終了して再起動
lsof -ti:3000 | xargs kill -9

# 環境変数の確認
echo $PORT

# .env ファイルの確認
cat .env | grep PORT

よくある間違い

  • Docker内で localhost を使用(代わりにサービス名を使用)
  • 127.0.0.1 と 0.0.0.0 の違いを理解していない
  • 環境変数でポートが上書きされている
  • 複数のサービスが同じポートを使用

Network の他のエラー

最終更新: 2025-12-09