Django, Docker, Python - Unable to install Pillow on python-alpine

For anyone who is interested in what worked for me (+ some background on why I ran into this):

Installing Pillow will require several dependencies. As far as I can tell, you need: gcc python3-dev jpeg-dev zlib-dev

To prevent these dependencies from ending up in the final image (keeping the image-size small) you can install some (not all!) of them in a virtual package.

After Pillow is installed successfully you can delete the dependencies that are only required for Pillow's installation.

Dependencies that are only needed during the build are called build dependencies.

So this is the code that worked for me:

RUN apk update \
    && apk add --virtual build-deps gcc python3-dev musl-dev \
    && apk add postgresql \
    && apk add postgresql-dev \
    && pip install psycopg2 \
    && apk add jpeg-dev zlib-dev libjpeg \
    && pip install Pillow \
    && apk del build-deps

(Some of the stuff is not required for Pillow, e. g. postgressql, postgresql-dev). As you can see, I installed my build dependencies in a virtual package called build-deps. AFTER installing the build dependencies, I am installing Pillow. At the end, I am removing the build dependencies.

I think, this is the solution that @LinPy proposed: I just wanted to explain this in a very verbose way to help others.

What is .build-deps for apk add --virtual command?


I just added these lines to my Dockerfile and it worked

RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers
RUN apk add --no-cache jpeg-dev zlib-dev
RUN apk del .tmp

My Dockerfile (using python:3.8-alpine):

COPY ./requirements.txt /requirements.txt
RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers
RUN apk add --no-cache jpeg-dev zlib-dev
RUN pip install -r /requirements.txt
RUN apk del .tmp

add this to your Dockerfile:

RUN apk add --no-cache jpeg-dev zlib-dev
RUN apk add --no-cache --virtual .build-deps build-base linux-headers \
    && pip install Pillow

source: Github