Add a python package in an existing non-python alpine image

Context #

I need to add a python package to an existing docker alpine image.

Solution #

There is a couple of caveats with the solution, which I share below:

  • alpine does not have a python package. Instead, it ships a python3 package instead.
  • The python installation does not include pip. It is another standalone package called py3-pip
  • python3 package doesn't add python to the path (it adds python3 instead), but py3-pip does add pip to the path.

A simplified Dockerfile, looks like:

FROM image:alpine

RUN apk update && apk add --update --no-cache \
python3 \ #Install the latest version of python 3
py3-pip && \ # Installs pip since it isn't packaged with python
ln -sf python3 /usr/bin/python # Makes 'python' available in path

WORKDIR terraform

COPY ./requirements.txt ./

RUN pip install -r requirements.txt

Reference #

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.