Docker image with two different python versions

Hello Community,

FROM public.ecr.aws/lambda/python:3.8

check our python environment

RUN python --version
RUN pip --version

Copy function code

COPY requirements/requirements-prod.txt ${LAMBDA_TASK_ROOT}/requirements.txt
COPY src/handler.py ${LAMBDA_TASK_ROOT}/handler.py
COPY src/ ${LAMBDA_TASK_ROOT}/src

RUN python3.8 -m pip install -r requirements.txt --target “${LAMBDA_TASK_ROOT}”

Set the CMD to your handler

CMD [“handler.profile”]

Question

I have been using the above template to build docker images and deploy on AWS Lambda. This template is working for me, but now I would like to deploy different versions of python (ex: python 3.8 and python 3.11.5) and different versions of requirements.txt files for each of the python versions mentioned above.

Is it possible to build two different versions using same Dockerfile? If yes how can I format the Dockerfile to reflect the same?

Thanks in advance.

You can use build arguments to specify the python version

https://docs.docker.com/reference/dockerfile/#arg

and place your different files in different folders containing the python version like:

./files/common/
./files/python-3.8/
./files/python-3.5/

Example:

ARG PYTHON_VERSION
FROM public.ecr.aws/lambda/python:${PYTHON_VERSION}
ARG PYTHON_VERSION

COPY ./files/common/ /files/
COPY ./files/python-${PYTHON_VERSION}/ /files/

RUN python${PYTHON_VERSION} ....
docker build . --build-arg PYTHON_VERSION=3.8 -t tag

ARG must be defined before and after FROM so you can use it in the FROM instruction and also after it.