0
votes

I have a python script that I'd want to run on 2 different containers running python 2.7 and python 3.6.

I want to use the same docker file to build 2 different images, with the difference being the python version(i.e one time it's FROM python:3.6 and the other is FROM python:2.7, and do it through a makefile.

Makefile

.PHONY = all clean build run

all: build run

# DOCKER TASKS
# Build the container
build: ## Build the container for tests
        docker build -t myscript:python2.7 .
        docker build -t myscript:python3.6 .
run: ## Run container
        docker run myscript:python2.7
        docker run myscript:python3.6

I have a Dockerfile for building the image: Dockerfile

FROM python:3.6

WORKDIR /usr/local/bin
RUN pip install pytest
COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]

Since it's the same Docker file it's tricky, I was thinking to create two different Dockerfiles each with a different python version (and all the rest the same), but was wondering if there's more elegant way to do it.

thanks

2

2 Answers

0
votes

You can use a build argument for it.

Your Dockerfile should look like this:

ARG VERSION=3.6

FROM python:3.6

WORKDIR /usr/local/bin
RUN pip install pytest
COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]

To build for 3.6:

docker build -t python-app:3.6 .

To build for 2.7:

docker build -t python-app:2.7 --build-arg VERSION=2.7 .

Note that 3.6 is the default version in case you don't specify one (ARG VERSION=3.6). You can also not assign a default value in which case you have to always pass a value in the build argument (--build-arg VERSION=...)

0
votes

you can try updating the script mentioned above like

ARG PYTHON_VERSION=python:3.8-slim-buster

FROM python:${PYTHON_VERSION}

WORKDIR /usr/local/bin RUN pip install pytest COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]