🍄

Next.jsを使う際にToo many open filesエラーが出て最終的に解消した話

に公開

こんにちは。1m4nim(いまにむ)です。本日は私が嵌ってしまったエラーのお話をします。

Too many open filesは何を伝えてきているか

  • Next.jsの揮発サーバーであるTurbopackが予期しないエラーで停止
  • 同時に開けるファイル数を超えてしまった

どうすればよいのか part1

プロセスごとに、開けるファイル数をコマンドで増やす

ulimit -n 4096

デフォルトが1024になっている場合が多いので40968192にすると解消する場合がある

どうすればよいのか part2

引き上げてもだめなとき(私の場合、ulimit -n 16384がだめでした)
bash: ulimit: open files: cannot modify limit: Operation not permitted

  • まずは現在のユーザーアカウントで設定できる最大値を確認
    ulimit -Hn

もしも永続的にユーザーの制限を増やす方法もある
sudo nano /etc/security/limits.conf

# ユーザー 1m4nim の制限を設定
1m4nim       soft    nofile      65536
1m4nim       hard    nofile      65536

システムに反映させるためにログアウト、ログインをする

1m4nim@1m4nim:~/1m4nim-article$ ulimit -Hn
4096

つまり開発サーバーに設定できるファイル記述子は4096である

ファイル記述子の消費が激しい原因は、Next.jsが不必要なファイルを監視しようとしている点にある
/home/1m4nim/package-lock.json
/home/1m4nim/1m4nim-article/package-lock.json
↑これらが**/home/1m4nim/1m4nim-article**にある場合、親ディレクトリにあるロックファイルは不要

rm /home/1m4nim/package-lock.json
rm -rf node_modules .next
npm install 
npm run dev

どうすればいいのか part3

ユーザーアカウントの制限の引き上げ (/etc/security/limits.conf)

  • limits.confの編集

    sudo nano /etc/security/limits.conf
    

    ファイルの末尾に追加

    1m4nim       soft    nofile      65536
    1m4nim       hard    nofile      65536
    

    現在のターミナルセッションを閉じて、再度ログイン

    システム全体の上限の引き上げ (/etc/sysctl.conf)

    sudo nano /etc/sysctl.conf
    

    ファイル内に fs.file-max の行があるか確認し、無ければファイルの末尾に追加

    fs.file-max = 1048576
    

    以下のコマンドで設定を読み込ませる

    sudo sysctl -p
    

    どうすればいいのか part4

    Turbopackが原因?

    Next.jsのダウングレード

    {
    "name": "1m4nim-article",
    "version": "0.1.0",
    "private": true,
    "scripts": {👇
      "dev": "NEXT_WEBPACK_CACHE_NAME=next-webpack-cache next dev",
      "build": "next build",
      "start": "next start",
      "lint": "next lint"
    },
    "dependencies": {
      "next": "14.2.3",
      "react": "18.2.0",
      "react-dom": "18.2.0",
      "styled-jsx": "^5.1.7"
    },
    "devDependencies": {
      "@tailwindcss/postcss": "^4",
      "@types/node": "^20.19.25",
      "@types/react": "^18.3.27",
      "@types/react-dom": "^18.2.0",
      "eslint": "8.57.0",
      "eslint-config-next": "14.2.3",
      "tailwindcss": "^4",
      "typescript": "^5"
    }
    
    npm install
    npm run dev
    

どうすればいいのか part4

next.config.tsをnext.config.jsへ

1m4nim@1m4nim:~/1m4nim-article$ mv next.config.ts next.config.js
この書き方知らなかった...
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // すべての設定を削除し、空のオブジェクトを返す
  experimental: {},
};

module.exports = nextConfig;

どうしたらいいのか part5

sudo nano /etc/sysctl.conf

ファイル末尾に

fs.inotify.max_user_watches = 524288
fs.inotify.max_user_instances = 512

保存したら

sudo sysctl -p
npm run dev

結び

Next.jsを用いて作りたいものがあり、サクサク進める予定でしたが落とし穴に嵌ってしまいました。次回の教訓として記事に書き起こしました。わかっていない部分も多くあるので、不備がありましたらお教えいただけると幸いです。

以上です〜!

Discussion