Posts Error installing mysql2: Failed to build gem native extension
Post
Cancel

Error installing mysql2: Failed to build gem native extension

Error installing mysql2: Failed to build gem native extension

Installing the mysql2 gem can be challenging, especially when building the native extension fails due to missing dependencies. This tutorial will show you how to resolve this issue on Ubuntu/Debian-based distributions.

Prerequisites

Make sure you have Ruby and Bundler installed on your system. If not, you can install them using the following commands:

1
2
3
sudo apt-get update
sudo apt-get install ruby-full
sudo gem install bundler

Step-by-Step Solution

  1. Install the Required Dependency

    The mysql2 gem needs the MySQL development package to compile the native extension. Run the command below to install the necessary dependency:

    1
    
    sudo apt-get install libmysqlclient-dev
    
  2. Install the mysql2 Gem

    With the dependency installed, you can now install the mysql2 gem:

    1
    
    gem install mysql2
    

    If you are using Bundler, add the gem to your Gemfile and run bundle install:

    1
    
    gem 'mysql2', '~> 0.5'
    
    1
    
    bundle install
    

Common Troubleshooting

  • Error: mysql.h file not found

    This error indicates that the MySQL header file is not available. Ensure the libmysqlclient-dev package is correctly installed.

    1
    
    sudo apt-get install libmysqlclient-dev
    
  • Permission Error

    If you encounter permission errors when installing the gem, try using sudo:

    1
    
    sudo gem install mysql2
    

Conclusion

By following the steps above, you should be able to install the mysql2 gem without issues. This process ensures all necessary dependencies are present, allowing the native extension to build correctly.

If you continue to experience problems, check the official mysql2 gem documentation or seek help from communities like Stack Overflow.


We hope this tutorial has been helpful. If you have any questions or suggestions, please leave a comment below!

This post is licensed under CC BY 4.0 by the author.