Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker Alpine: Error loading MySQLdb module

I am building an Alpine based image of a Django application with MariaDB and I can't figure out which dependency I should add to my Dockerfile so that my app could properly connect to the DB.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

Well, I thought I did. From what I read in this article, in this discussion, mariadb-dev is in Alpine the equivalent of default-libmysqlclient-dev in Debian based system. Furthermore, the mysql-client package in Alpine is merely a dummy package (containing mariadb-dev, mariadb-client, etc etc). Here is the Dockerfile:

# pull official base image
FROM python:3.7-alpine

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# set work directory
WORKDIR /usr/src/cms

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

# install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
COPY ./Pipfile /usr/src/cms/Pipfile
RUN pipenv install --skip-lock --system --dev

# copy entrypoint.sh
COPY ./entrypoint.sh /usr/src/cms/entrypoint.sh

# copy project
COPY . /usr/src/cms/

# run entrypoint.sh
ENTRYPOINT ["/usr/src/cms/entrypoint.sh"]

I tried to add mariadb-client, to use mysql-client instead. I also tried to add RUN pip install django-mysql. Nothing seems to change. I successfully build Postgres Django apps without any problem but, when it comes to MySQl vs MariaDB // Debian vs Alpine, I feel confused. Any insight?

like image 716
zar3bski Avatar asked May 08 '19 20:05

zar3bski


2 Answers

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
like image 187
valiano Avatar answered Sep 21 '22 09:09

valiano


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
like image 43
Gunjan Avatar answered Sep 19 '22 09:09

Gunjan