How do I install python on alpine linux?

Viewed 170921

How do I install python3 and python3-pip on an alpine based image (without using a python image)?

 $ apk add --update python3.8 python3-pip
 ERROR: unsatisfiable constraints:
   python3-pip (missing):
     required by: world[python3-pip]
   python3.8 (missing):
     required by: world[python3.8]
7 Answers

This is what I use in a Dockerfile for an alpine image:

# Install python/pip
ENV PYTHONUNBUFFERED=1
RUN apk add --update --no-cache python3 && ln -sf python3 /usr/bin/python
RUN python3 -m ensurepip
RUN pip3 install --no-cache --upgrade pip setuptools

instead of python3-pip install py3-pip

apk add --update python3 py3-pip

You can try this command:

apk add python3

You may use the python official image which offers alpine tags as well. You will probably get the most state-of-the-art python install:

e.g.:

FROM python:3-alpine

Additional option is to build python during image build:

FROM alpine:latest

# you can specify python version during image build
ARG PYTHON_VERSION=3.9.9

# install build dependencies and needed tools
RUN apk add \
    wget \
    gcc \
    make \
    zlib-dev \
    libffi-dev \
    openssl-dev \
    musl-dev

# download and extract python sources
RUN cd /opt \
    && wget https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz \                                              
    && tar xzf Python-${PYTHON_VERSION}.tgz

# build python and remove left-over sources
RUN cd /opt/Python-${PYTHON_VERSION} \ 
    && ./configure --prefix=/usr --enable-optimizations --with-ensurepip=install \
    && make install \
    && rm /opt/Python-${PYTHON_VERSION}.tgz /opt/Python-${PYTHON_VERSION} -rf
                                                                                                                                                                                                                                               # rest of the image, python3 and pip3 commands will be available

This snippet downloads and builds python of specified version from sources (together with pip). It may be an overkill but sometimes it may come in handy.

It looks like you're trying to install a specific minor version of Python3 (3.8), you can do this in Alpine by using semver like this which will install a version of python3>=3.8.0 <3.9.0-0:

apk add python3=~3.8
Related