Solution 1:

You've installed the python-dev libraries for Python 3. Your psycopg2 install is using python 2.7

Make sure you've installed python3-pip

sudo apt-get install python3-pip

Then:

pip3 install psycopg2

If that still fails, try installing the development headers for postgresql:

sudo apt install python3-dev libpq-dev
pip3 install psycopg2

If on Python 2

sudo apt update
sudo apt-get install postgresql postgresql-contrib
sudo apt-get install libpq-dev
sudo apt-get install python-dev
sudo apt-get install python-pip
pip2 install psycopg2-binary

If on Ubuntu 20.04

sudo apt-get install build-essential

Then run the other steps for either Python 2 or 3.

Solution 2:

I was testing my application on a ubuntu docker image that only has python2.7.6 installed (as happens in most big orgs)

If you are using python2.x (though you should plan to move to 3.x asap), check the below dependencies:

sudo apt update
sudo apt-get install postgresql postgresql-contrib
sudo apt-get install libpq-dev # this is required as psycopg2 uses pg_config
sudo apt-get install python-dev
sudo apt-get install python-pip

Now install psycopg2 using:

pip2 install psycopg2-binary

Solution 3:

I had the same error trying to install it in a virtualenv (with python3)

I solved it by installing a previous version of psycopg2.

pip install psycopg2==2.7.5