Using psycopg2 in Azure Functions

If you wish to interface with any PostgreSQL DB within Azure functions, you may have tried to include psycopg2 in the requirements.txt file. Your code may work perfectly locally, but you may get an error similar to the following when you check Azure Function logs:

ImportError: cannot open shared object file: No such file or directory

The extended path of the error will finally point to the

import psycopg2

line in your code. What is the solution?

Simple. Use psycopg2-binary instead of psycopg2. The only change you need to make is in requirements.txt.

Instead of




Of course, you may want to check the latest version, or use an older version depending on your requirements. If you don’t wish to dig any further, you can stop reading here.

However, if you do wish to know why psycopg2 doesn’t work but psycopg2-binary works, here’s the explanation:

psycopg2 is not a standalone package. It is built using libpq-dev package, during installation. Now, psycopg2 depends on the host OS to find this library. And Azure Functions don’t have libpq, as the error above clearly indicates.

You may be wondering that we can perhaps simply add libpq-dev to requirements.txt. But that doesn’t work. You will get the error:

No matching distribution found for libpq-dev

Thus, the required solution is to use a package of psycopg2 that doesn’t require libpq. psycopg2-binary is exactly that. I hope this provided a satisfactory explanation.

You can refer to the following links for more details:


If you liked this article, you may check out other articles related to Azure here:

If you are planning to appear for the Azure Administrator Exam Certification, check out this course on Udemy.


Leave a comment

Your email address will not be published. Required fields are marked *