pythondockershelldockerfilecontainers

Dynamically copy from base image with a build arg?


I'm trying to dynamically choose which base to copy from based on a build argument, here's a stripped version my Dockerfile:

ARG PY_VER=3.12
ARG BUILD=default

# Build stage
FROM python:${PY_VER}-slim AS base_default

RUN pip install --no-cache-dir --upgrade gunicorn

# Deploy stage
FROM python:${PY_VER}-slim AS build_default
ARG PY_VER
ARG BUILD

COPY --from=base_${BUILD} /usr/local/bin/gunicorn /usr/local/bin/gunicorn

COPY --from=base_${BUILD} /usr/local/lib/python${PY_VER}/site-packages/ /usr/local/lib/python${PY_VER}/site-packages/

CMD ["gunicorn", "-h"]

It's fine with the PY_VER argument but BUILD unfortunately gives an error like:

Test:16
--------------------
  14 |     COPY --from=base_${BUILD} /usr/local/bin/gunicorn /usr/local/bin/gunicorn
  15 |     
  16 | >>> COPY --from=base_${BUILD} /usr/local/lib/python${PY_VER}/site-packages/ /usr/local/lib/python${PY_VER}/site-packages/
  17 |     
  18 |     CMD ["gunicorn", "-h"]
--------------------
ERROR: failed to solve: failed to parse stage name "base_${BUILD}": invalid reference format: repository name (library/base_${BUILD}) must be lowercase

Can anything be done to get it working?


Solution

  • So just proxy it.

    ARG PY_VER=3.12
    ARG BUILD=default
    # Build stage
    FROM python:${PY_VER}-slim AS base_default
    RUN pip install --no-cache-dir --upgrade gunicorn
    
    FROM base_${BUILD} as the_chosen_base
    
    FROM python:${PY_VER}-slim AS build_default
    ARG PY_VER
    ARG BUILD
    COPY --from=the_chosen_base /usr/local/bin/gunicorn /usr/local/bin/gunicorn
    
    COPY --from=the_chosen_base /usr/local/lib/python${PY_VER}/site-packages/ /usr/local/lib/python${PY_VER}/site-packages/