MeWrite Docs

Linux: Too many open files

プロセスがオープンできるファイルディスクリプタの上限に達した場合のエラー

概要

プロセスがオープンできるファイルディスクリプタ(ファイル、ソケット、パイプ等)の数が上限に達した場合に発生するエラーです。高負荷なWebサーバーやデータベースで頻繁に発生します。

エラーメッセージ

Too many open files
java.io.IOException: Too many open files
Error: EMFILE, too many open files
socket: Too many open files
accept: Too many open files

原因

  1. ulimitの制限値が低い: デフォルト値(通常1024)が不足
  2. ファイルディスクリプタのリーク: ファイルやソケットをclose()していない
  3. 大量の同時接続: Webサーバーやプロキシで接続数が多い
  4. システム全体のファイル数上限: カーネルパラメータ fs.file-max の制限

解決策

1. 現在の制限値を確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 現在のプロセスのソフト/ハードリミット
ulimit -Sn   # ソフトリミット
ulimit -Hn   # ハードリミット

# 特定プロセスの制限値
cat /proc/<PID>/limits | grep "open files"

# 特定プロセスが開いているファイル数
ls /proc/<PID>/fd | wc -l

# システム全体の使用状況
cat /proc/sys/fs/file-nr
# 出力: 使用中 / 未使用 / 最大値

2. ulimitを一時的に変更

1
2
3
4
5
# 現在のシェルセッションで変更
ulimit -n 65536

# 特定コマンドの実行時に変更
ulimit -n 65536 && /usr/local/bin/myapp

3. limits.confで永続的に変更

1
2
# /etc/security/limits.conf
# または /etc/security/limits.d/99-custom.conf
# ユーザー単位
myapp    soft    nofile    65536
myapp    hard    nofile    65536

# 全ユーザー
*        soft    nofile    65536
*        hard    nofile    65536
1
2
3
# PAMの設定確認(limits.confを有効にするために必要)
grep pam_limits /etc/pam.d/common-session
# session required pam_limits.so が必要

4. systemdサービスの制限値を変更

1
2
3
# /etc/systemd/system/myapp.service
[Service]
LimitNOFILE=65536
1
2
sudo systemctl daemon-reload
sudo systemctl restart myapp.service

5. カーネルパラメータの変更

1
2
3
4
5
6
7
8
9
# 現在のシステム全体の上限確認
sysctl fs.file-max

# 一時的に変更
sudo sysctl -w fs.file-max=2097152

# 永続化
echo "fs.file-max = 2097152" | sudo tee -a /etc/sysctl.d/99-custom.conf
sudo sysctl -p /etc/sysctl.d/99-custom.conf

6. ファイルリークの調査

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# プロセスが開いているファイル一覧
sudo lsof -p <PID>

# ファイルタイプ別の集計
sudo lsof -p <PID> | awk '{print $5}' | sort | uniq -c | sort -rn

# ソケット接続の確認
sudo lsof -p <PID> -i

# 全プロセスのファイルディスクリプタ使用数ランキング
for pid in /proc/[0-9]*; do
  echo "$(ls $pid/fd 2>/dev/null | wc -l) $pid $(cat $pid/comm 2>/dev/null)"
done | sort -rn | head -20

関連エラー

Linux の他のエラー

最終更新: 2026-02-03