🏗️

【頻出】mysql2 gemがインストールに失敗したときの解決方法

に公開2

問題

railsではmysql2のgemはよく使うのですが、これよくビルドに失敗するんですよね。

全部のプロジェクトがDocker化されていて、環境をPortableにする仕組みが整っていれれば素晴らしいのですが、現実はそのようにはいきません。

なのでいくつかのプロジェクトでは、Mac環境下でRails開発を行っていくことになります。

この記事では、gem mysql2をbundle installしようとしたときにコンパイルに失敗してbundle installが完了できない問題の解決策を書きます。

解決プロセス

コマンドで brew info openssl を打ちます

openssl@1.1: stable 1.1.1d (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/openssl@1.1/1.1.1d (7,983 files, 17.9MB)
Poured from bottle on 2019-09-25 at 12:59:29
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/openssl@1.1.rb
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
/usr/local/etc/openssl@1.1/certs

and run
/usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because openssl/libressl is provided by macOS so don't link an incompatible version.

If you need to have openssl@1.1 first in your PATH run:
echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@1.1 you may need to set:
export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

For pkg-config to find openssl@1.1 you may need to set:
export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"

==> Analytics
install: 410,459 (30 days), 1,382,523 (90 days), 3,038,465 (365 days)
install-on-request: 63,098 (30 days), 183,588 (90 days), 495,271 (365 days)
build-error: 0 (30 days)

ご丁寧にコンパイラがOpenSSLを見つけるためのパスが書いてあります。

export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

この部分ですね。

bundle configの設定の修正&再ビルド

$ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl@1.1/lib"
$ bundle config --local build.mysql2 "--with-cppflags=-I/usr/local/opt/openssl@1.1/include"

これでMySQLを動かすための準備は整ったので、改めて bundle installで通せば完了!

Discussion

Yukito OhiraYukito Ohira

20250917現在 Cursorに直させた

Exported on 2025/9/17 at 2:30:05 JST from Cursor (1.6.23)


User

fix this error


Cursor

このエラーは mysql2 gem のインストール時に zstd ライブラリが見つからないことが原因です。macOS でよくある問題で、以下の手順で解決できます。

まず、zstd ライブラリをインストールします:

zstd は既にインストールされているようですが、mysql2のビルド設定を更新する必要があります。現在の設定を確認して、適切な設定に変更しましょう:

次に、mysql2のgemをクリーンアップしてから再インストールします:

素晴らしい!エラーが解決されました。bundle install が正常に完了し、mysql2 gem が正常にインストールされました。

解決した内容

  1. zstdライブラリの確認: zstd は既にインストールされていました
  2. mysql2のビルド設定を更新: Homebrewの標準的なパス(/opt/homebrew/lib/opt/homebrew/include)を使用するように設定を変更しました
  3. gemの再インストール: 新しい設定で bundle install を実行し、mysql2が正常にインストールされました

この問題は、macOSでHomebrewを使用している場合に、mysql2 gemが正しいライブラリパスを見つけられないことが原因でした。Homebrewの標準的なパスを指定することで解決できました。

これで bundle install が正常に動作するようになり、プロジェクトの依存関係がすべてインストールされました。

Yukito OhiraYukito Ohira
bundle config build.mysql2 --with-ldflags=-L/opt/homebrew/lib --with-cppflags=-I/opt/homebrew/include