Run python mysql client on slim python 3.6 docker image

Question:

I have a working service running on a python:3.6-jessie image.
I am trying to reduce the size of it to speed up serverless cold starts.

I have tried the images python:3.6-alpine, python:3.6-slim-buster and python:3.6-slim-jessie.

With all of them I end up having to install many additional packages and I end up with the follwing error that I cannot fix with more packages:

ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory

My current Dockerfile is

FROM python:3.6-jessie as build

ENV PYTHONUNBUFFERED 0
ENV FLASK_APP "api/app.py"

RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /opt/venv

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

FROM python:3.6-slim-jessie
COPY --from=build /opt/venv /opt/venv
WORKDIR /opt/venv
RUN apt-get update
RUN apt-get --assume-yes install gcc
RUN apt-get --assume-yes install python-mysqldb

ENV PATH="/opt/venv/bin:$PATH"

RUN rm -rf configs tests draw_results env .idea .git .pytest_cache

EXPOSE 8000

CMD ["/opt/venv/run.sh"]

The relevant lines from requirements.txt:

mysqlclient==1.4.2.post1
PyMySQL==0.9.3
Flask-SQLAlchemy==2.3.2
SQLAlchemy==1.3.0

The run.sh is just my gunicorn start command.

Is there any package I can use to fix this last issue, is there some other mysql library I should be using or some other way for me to fix this. Or should I just stick to full python:3.6 images when I want a mysql client?

Asked By: Stian

||

Answers:

Try to add this line to the dockerfile:

RUN apt-get install -y libmysqlclient-dev
Answered By: Evhz

I’m using python:3.7-slim and using the following command

RUN apt-get -y install default-libmysqlclient-dev

Answered By: ssi-anik

For python slim-buster (debian os) use can run this command on Dockerfile.

RUN apt-get update && apt-get install -y default-mysql-client

This worked for me.
I have used python:3.10.6-slim-buster

Answered By: Subhransu Das