その他

mysqlがインストールできない

Rails で開発をしていると、mysqlがインストールできないといったエラーに悩まされることが多いと思います。

以下のエラーが出たときの対処法になります。

An error occurred while installing mysql2 (0.5.3), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.3' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
mysql2

このとき、エラー文の中に ld: library not found for -lssl があれば今回の記事の通りにやれば解決できると思います!

エラーの原因

エラー文にある通り、openssl のパスが見つからないことです。

エラーの解決方法

まずは brew info openssl でパスを探します。

$ brew info openssl
==> openssl@3: stable 3.2.0 (bottled)
Cryptography and SSL/TLS Toolkit

/opt/homebrew/Cellar/openssl@3/3.2.0_1 (6,805 files, 31.9MB) *
  Poured from bottle using the formulae.brew.sh API on 2023-12-19 at 09:56:54
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/o/openssl@3.rb
License: Apache-2.0
==> Dependencies
Required: ca-certificates ✘
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /opt/homebrew/etc/openssl@3/certs

and run
  /opt/homebrew/opt/openssl@3/bin/c_rehash
==> Analytics
install: 494,281 (30 days), 1,384,856 (90 days), 3,017,484 (365 days)
install-on-request: 77,063 (30 days), 199,175 (90 days), 500,713 (365 days)
build-error: 4,702 (30 days)

ここからパスが /opt/homebrew/Cellar/openssl@3/3.2.0_1 であることが分かります。

これで以下のコマンドを入力することで、mysql2 Gem のビルドの設定を更新することができます。(パスの部分を brew info の情報で得られたパスと置き換えてください。)

bundle config --local build.mysql2 "--with-ldflags=-L/opt/homebrew/Cellar/openssl@3/3.2.0_1/lib --with-cppflags=-I/opt/homebrew/Cellar/openssl@3/3.2.0_1/include"

これで、mysql2 が無事にインストールされたら完了です。

ABOUT ME
酒井 駿
名古屋工業大学大学院卒業後、豊田合成(株)で品質管理を経験し、その後スタートアップ・マネーフォワードを経て、2024年11月に株式会社EGGHEAD創業。 製造業とエンジニアリング、両方の現場の知見を活かし、製造業における生成AIを活用した業務改善やシステム開発を支援します。