[Fixed]-Docker Alpine: Error loading MySQLdb module


It seems you’re missing the MySQLdb Python module, for which you should install the mysqlclient Python package: pip install mysqlclient.

On Alpine, pip will build mysqlclient from source, so you’ll need gcc and musl-dev for this setup step, hence you’ll need to postpone apk del build-deps to after Python modules are installed.

Fixed Dockerfile snippet:

RUN apk update \
    && apk add --virtual build-deps gcc python3-dev musl-dev \
    && apk add --no-cache mariadb-dev


RUN pip install mysqlclient  

RUN apk del build-deps


Mainly you need to install mariadb-connector-c-dev package. But only this package will give compilation errors. So additionally you will need to add gcc and musl-dev packages into Dockerfile. This will make Django and MySQL work within alpine image.

FROM python:3.8-alpine

RUN apk add gcc musl-dev mariadb-connector-c-dev


2023.05.06 – 2023.06.08
During this time I explicitly used the following code and it worked:

RUN apk add musl-dev mariadb-connector-c-dev gcc && \
    pip install mysqlclient && \
    pip cache purge && \
    apk del --rdepends --purge musl-dev gcc

But now, 2023.06.25, I found that I had to add mariadb-dev to successfully install mysqlclient.

Leave a comment