【问题标题】:Setting conditional variables in a Dockerfile在 Dockerfile 中设置条件变量
【发布时间】:2022-01-17 01:39:57
【问题描述】:

我正在尝试使用 predefined TARGETARCH arg 变量通过 buildkit 创建多架构 docker 映像。

我想要做的是 - 我认为 - 类似 bash 变量间接的东西,但我知道这不受支持,我正在努力想出一个替代方案。

这是我得到的:

FROM alpine:latest

# Buildkit should populate this on build with e.g. "arm64" or "amd64"
ARG TARGETARCH

# Set some temp variables via ARG... :/
ARG DOWNLOAD_amd64="x86_64"
ARG DOWNLOAD_arm64="aarch64"

ARG DOWNLOAD_URL="https://download.url/path/to/toolkit-${DOWNLOAD_amd64}"

# DOWNLOAD_URL must also be set in container as ENV var.
ENV DOWNLOAD_URL $DOWNLOAD_URL

RUN echo "Installing Toolkit" && \
    curl -sSL ${DOWNLOAD_URL} -o /tmp/toolkit-${DOWNLOAD_amd64}

... 这有点伪代码,但希望能说明我正在尝试做的事情:我希望 $DOWNLOAD_amd64$DOWNLOAD_arm64 的值下降到 $DOWNLOAD_URL,这取决于 $TARGETARCH 是什么设置为。

这可能是一个长期解决的问题,但要么我在谷歌上搜索错误的东西,要么就是没有得到它。

【问题讨论】:

  • 这个 dockerfile 是否应该仅适用于 arm64amd64
  • 这是目前唯一的要求,尽管添加更多的灵活性会很好。

标签: docker dockerfile multiarch


【解决方案1】:

好的,不完整。这是一个完整的工作解决方案:

Dockerfile:

FROM ubuntu:18.04

ARG TARGETARCH

ARG DOWNLOAD_amd64="x86_64"
ARG DOWNLOAD_arm64="aarch64"
WORKDIR /tmp
ARG DOWNLOAD_URL_BASE="https://download.url/path/to/toolkit-"
RUN touch .env; \
    if [ "$TARGETARCH" = "arm64" ]; then \
    export DOWNLOAD_URL=$(echo $DOWNLOAD_URL_BASE$DOWNLOAD_arm64) ; \
    elif [ "$TARGETARCH" = "amd64" ]; then \
    export DOWNLOAD_URL=$(echo $DOWNLOAD_URL_BASE$DOWNLOAD_amd64) ; \
    else \
    export DOWNLOAD_URL="" ; \
    fi; \
    echo DOWNLOAD_URL=$DOWNLOAD_URL > .env; \
    curl ... #ENVS JUST VALID IN THIS RUN!
 
COPY ./entrypoint.sh ./entrypoint.sh
ENTRYPOINT ["/bin/bash", "entrypoint.sh"]

入口点.sh

#!/bin/sh

ENV_FILE=/tmp/.env
if [ -f "$ENV_FILE" ]; then
    echo "export " $(grep -v '^#' $ENV_FILE | xargs -d '\n') >> /etc/bash.bashrc
    rm $ENV_FILE
fi

trap : TERM INT; sleep infinity & wait

测试:

# bash
root@da1dd15acb64:/tmp# echo $DOWNLOAD_URL
https://download.url/path/to/toolkit-aarch64

现在是 Alpine:

Dockerfile

FROM alpine:3.13
RUN apk add --no-cache bash

入口点.sh

ENV_FILE=/tmp/.env
if [ -f "$ENV_FILE" ]; then
    echo "export " $(grep -v '^#' $ENV_FILE) >> /etc/profile.d/environ.sh
    rm $ENV_FILE
fi

Alpine 不接受xargs -d。但这里没有那么有趣,因为 URL 不包含任何空白..

测试: Alpine 仅将其用于登录 shell。所以:

docker exec -it containername sh --login
echo $DOWNLOAD_URL

【讨论】:

  • 导出的DOWNLOAD_URL 不会传播到后续的RUN 指令。
  • 是的,这可以用来执行安装步骤,即将它包裹在 curl 命令周围,但是如何在构建的映像中将 $DOWNLOAD_URL 设置为 ENV var?
  • @Wintermute:我会通过相同的 RUN 语句创建一些 .env 文件并将其加载到入口点。
  • 在镜像中运行curl 后,您可以将其解压到一个已知的独立于架构的路径(/opt/toolkit/usr/local),此时您不需要知道不再是原来的网址了。
  • 好的,谢谢大家的回复。我想上面是目前可用的最优雅的方式,所以这就是我将采用的方式:)
猜你喜欢
  • 2019-09-11
  • 2011-12-28
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多