Search code examples
pythonpython-3.xdockerpipdockerfile

Make Docker container use newest version of Python installed


I have a couple of Python modules that I use inside my Docker container and they require a higher version of Python that what's being used. I install Python and install the modules using:

RUN apt-get update || : && apt-get install python3 -y
RUN apt-get install -y python3-pip
COPY requirements.txt /project
RUN pip3 install -r requirements.txt

Expecting I would be using the latest version of Python in my Docker container but when I go into it's shell and run python3 --version is comes as 3.4.2 which is incredibly old for my program. How do I make the default Python to be the latest I installed above without messing over the System-level python?

The image runtime I'm using for the Docker container is: node:9-slim


Solution

  • I don't think you can find a prebuilt python3.9 package on a debian 8 distribution as your environment is pretty old.

    The only solution is you build the python3.9 out from source code in your base container. A full workable Dockerfile as next:

    FROM node:9-slim
    
    RUN apt update; \
    apt install -y build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev; \
    wget https://www.python.org/ftp/python/3.9.7/Python-3.9.7.tgz; \
    tar -zxvf Python-3.9.7.tgz; \
    cd Python-3.9.7; \
    ./configure --prefix=/usr/local/python3; \
    make && make install; \
    ln -sf /usr/local/python3/bin/python3.9 /usr/bin/python3; \
    ln -sf /usr/local/python3/bin/pip3.9 /usr/bin/pip3
    

    Verify it:

    $ docker build -t myimage:1 .
    $ docker run --rm -it myimage:1 python3 --version
    Python 3.9.7
    $ docker run --rm -it myimage:1 pip3 --version
    pip 21.2.3 from /usr/local/python3/lib/python3.9/site-packages/pip (python 3.9)