Home > database >  Dockerfile support multiple from
Dockerfile support multiple from

Time:07-17

I have a need to run python on different CPU architectures such as AMD64 and ARM (Raspberry Pi) etc. I read the documentation from Docker that Multi Stage Build is probably the way to go.

FROM python:3.10-slim
LABEL MAINTAINER=XXX
ADD speedtest-influxdb.py /speedtest/speedtest-influxdb.py

ENV INFLUXDB_SERVER="http://10.88.88.10:49161"

RUN apt-get -y update
RUN python3 -m pip install 'influxdb-client[ciso]'
RUN python3 -m pip install speedtest-cli

CMD python3 /speedtest/speedtest-influxdb.py

FROM arm32v7/python:3.10-slim
LABEL MAINTAINER=XXX
ADD speedtest-influxdb.py /speedtest/speedtest-influxdb.py

ENV INFLUXDB_SERVER="http://10.88.88.10:49161"

RUN apt-get -y update
RUN python3 -m pip install 'influxdb-client[ciso]'
RUN python3 -m pip install speedtest-cli

CMD python3 /speedtest/speedtest-influxdb.py


But as you can see there's a bit to repetition. Is there a better way?

CodePudding user response:

A typical use of a multi-stage build is to build some artifact you want to run or deploy, then COPY it into a final image that doesn't include the build tools. It's not usually the right tool when you want to build several separate things, or several variations on the same thing.

In your case, all of the images are identical except for the FROM line. You can use an ARG to specify the image you're building FROM (in this specific case ARG comes before FROM)

ARG base_image=python:3.10-slim
FROM ${base_image}
...
CMD ["/speedtest/speedtest.py"]
# but only once

If you just docker build this image, you'll get the default base_image, which will use a default Python for the current default architecture. But you can request a different base image, or a different target platform

# Use the ARM32-specific image
docker build --build-arg base_image=arm32v7/python:3.10-slim .

# Force an x86 image (with emulation if supported)
docker build --platform linux/amd64 .
  • Related