I recently ran into a frustrating issue while trying to install the pg
gem for Ruby on Ubuntu. If you’ve landed here, chances are you’ve faced this annoying error too. The good news? I figured it out — and I’m going to walk you through the exact fix step by step.
How It Start
I was setting up a Ruby project and needed to connect it to PostgreSQL. Naturally, I installed Ruby using RVM and then ran:
gem install pg
But instead of a clean installation, I got hit with this scary wall of text:
Building native extensions. This could take a while...
ERROR: Error installing pg:
ERROR: Failed to build gem native extension.
checking for pg_config... yes
checking for libpq-fe.h... yes
...
Can't find the PostgreSQL client library (libpq)
What Went Wrong
At first, I panicked but then I dug deeper.
The pg
gem is basically a bridge between Ruby and PostgreSQL. To work properly, it depends on a C library called libpq, which is part of PostgreSQL. Even though I had Ruby installed, my system didn’t have the PostgreSQL development headers, so Ruby couldn’t compile the gem.
In short:
Ruby installed
PostgreSQL development libraries missing → Installation failed
The Fix
All I had to do was install the missing PostgreSQL libraries.
Update package list
sudo apt update
Install the required packages
sudo apt install libpq-dev
If PostgreSQL isn’t installed at all, install everything in one go:
sudo apt install postgresql postgresql-contrib libpq-dev
Try again
gem install pg
And boom no more errors!
Testing the Installation
To double-check that everything works, I created a simple Ruby file called test_pg.rb
:
require 'pg'
begin
conn = PG.connect(dbname: 'postgres', user: 'postgres')
puts "Connection successful!"
rescue PG::Error => e
puts "Connection failed: #{e.message}"
end
Run it using:
ruby test_pg.rb
If you see “Connection successful!”, you’re all set!
Bonus Practice Insert and Fetch Data Using Ruby + PostgreSQL
I didn’t stop there I wanted to make sure everything actually works in action. So I wrote this:
require 'pg'
conn = PG.connect(dbname: 'postgres', user: 'postgres')
# Create table
conn.exec("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(50));")
# Insert Data
conn.exec("INSERT INTO users (name) VALUES ('Alice'), ('Bob');")
# Read Data
res = conn.exec("SELECT * FROM users;")
res.each { |row| puts row }
puts "Data inserted and read successfully!"
This little test script helped me insert and retrieve real data which confirmed everything was working perfectly.
Final Thought
If you’re dealing with this error, don’t worry it’s not your fault. Ubuntu just doesn’t include PostgreSQL’s development libraries out of the box. Once you know what’s missing, the fix is simple. I hope this guide saved you from hours of confusion. If it helped, feel free to copy this solution into your own notes or share it with someone else who’s stuck.