[Django]-Failing to install psycopg2-binary on new docker container

24👍

On Alpine Linux, you will need to compile all packages, even if a pre-compiled binary wheel is available on PyPI. On standard Linux-based images, you won’t (https://pythonspeed.com/articles/alpine-docker-python/ – there are also other articles I’ve written there that might be helpful, e.g. on security).

So change your base image to python:3.8.3-slim-buster or python:3.8-slim-buster and it should work.

68👍

I made it work. This is the code:

FROM python:3.8.3-slim #Image python:3.9.5-slim also works # Image python:3.9.5-slim-buster also works

RUN apt-get update \
    && apt-get -y install libpq-dev gcc \
    && pip install psycopg2
    

11👍

This scripts work on MacBook Air M1

Dockerfile

FROM ubuntu:20.04
RUN apt-get update && apt-get -y install libpq-dev gcc && pip install psycopg2
COPY requirements.txt /cs_account/
RUN pip3 install -r requirements.txt

requirements.txt

psycopg2-binary~=2.8.6

Updated answer from the answer of Zoltán Buzás

5👍

This worked for me. Try slim-buster image.

In your Dockerfile

FROM python:3.8.7-slim-buster

and in your requirements.txt file

psycopg2-binary~= <<version_number>>

2👍

I added this to the top answer because I was getting other errors like below:

gcc: error trying to exec 'cc1plus': execvp: No such file or directory
error: command 'gcc' failed with exit status 1

and

src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
#include <sql.h>

This is what I did to fix this, so I am not sure how others were getting that to work, however maybe it was some of the other things I was doing?

My solution that I found from other posts when googling those two errors:

FROM python:3.8.3-slim 

RUN apt-get update \
&& apt-get -y install g++ libpq-dev gcc unixodbc unixodbc-dev

0👍

I’ve made a custom image with

FROM python:alpine
ADD requirements.txt /
RUN apk update --no-cache \
&& apk add build-base postgresql-dev libpq --no-cache --virtual .build-deps \
&& pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r /requirements.txt \
&& apk del .build-deps
RUN apk add postgresql-libs libpq --no-cache

and requirements.txt

django
djangorestframework
psycopg2-binary

0👍

To others that may have this problem – (I know OP doesn’t have this issue) but it could be that you are attempting to install psycopg2 instead of psycopg2-binary which was my problem.

Leave a comment