👌

Next.js の Docker 本番運用 Image 400 エラーの解決(“url” parameter is not allowed)

に公開

現象

Next.js の Docker 本番運用で画像最適化エンドポイント /_next/image へのアクセスで 400: "url" parameter is not allowed

よくある原因

  • Next.js の Image Optimization は、許可済みのリモート画像のみを処理します。next.config.jsimages.remotePatterns に該当の URL パターンが含まれていない場合、サーバー側で拒否され 400 になります。
  • Docker ビルド時に next.config.js をイメージへコピーし忘れ、実行時にデフォルト設定となってしまい、結果として 400 に繋がります。

解決の要点

  1. next.config.js に対象のリモート画像を許可する(images.remotePatterns 推奨)
  2. Dockerfile で next.config.js を確実にコピーする
  3. 本番起動は next start を使う(/_next/image を含むサーバー最適化が有効になる)

設定例(next.config.js)

const nextConfig = {
  images: {
    // より明確・安全に制限するなら remotePatterns を推奨
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.example.com',
        port: '',
        pathname: '/**',
      },
      {
        protocol: 'https',
        hostname: 'cdn.example.org',
        port: '',
        pathname: '/assets/**',
      },
    ],
  },
};
module.exports = nextConfig;

Dockerfile のポイント

# ソースと設定をコピー(next.config.ts を忘れずに)
COPY next.config.ts ./

CMD ["next", "start"]

まとめ

Vercel 以外でも、Next.js の Image Optimization は利用できます。

参考


  1. https://nextjs.org/docs/app/api-reference/components/image#src


  2. https://nextjs.org/docs/app/guides/self-hosting#image-optimization


  3. https://github.com/vercel/next.js/issues/18412#issuecomment-829462186

Discussion