多阶段dockerfile跳过阶段

时间:2020-08-12 13:07:29

标签: docker dockerfile docker-multi-stage-build

我正在尝试在后续阶段构建一个多阶段dockerfile,但是所有阶段都已执行。

即使我在docker build中指定了EXECUTION_ENV=local,我总是c git clone正在执行

Dockerfile:

ARG GIT_TOKEN=abc:1a2b3
ARG EXECUTION_ENV=local

# get dependencies from github
FROM alpine/git as gitclone-ci
WORKDIR /usr/src/
RUN git clone https://{GIT_USER_TOKEN}@github.com/something.git \
    && git clone https://{GIT_USER_TOKEN}@github.com/somethingelse.git

## in local dependencies are already available in the parent folder
FROM alpine/git as gitclone-local
WORKDIR /usr/src/
COPY ../something /usr/src/something 
COPY ../somethingelse /usr/src/somethingelse

FROM node:latest as builder
WORKDIR /usr/src
COPY --from=gitclone-${EXECUTION_ENV} /usr/src .
COPY package* ./
COPY src/ src/
RUN ["npm", "install"]

Docker build cmds尝试过:

docker build -t somecontainer --build-arg GIT_TOKEN=abc:123 --build-arg EXECUTION_ENV=local.

docker build -t somecontainer --target builder --build-arg GIT_TOKEN=abc:123 --build-arg EXECUTION_ENV=local.

注意: 如果我在docker守护进程中启用"features": { "buildkit": true}并运行cmd docker build -t somecontainer --build-arg GIT_TOKEN=abc:123 --build-arg EXECUTION_ENV=local.,则会出现以下错误

failed to solve with frontend dockerfile.v0: failed to create LLB definition: failed to parse stage name "gitclone-$EXECUTION_ENV": invalid reference format: repository name must be lowercase

1 个答案:

答案 0 :(得分:0)

跳过阶段仅适用于BuildKit。请参阅讨论here和文章here

对于您遇到的错误,应该使用BuildKit或不使用BuildKit来获取,因为您不能在COPY指令中使用生成参数。区别在于,使用BuildKit的Docker甚至会拒绝启动构建,没有Docker,构建将无法执行COPY指令。

您需要做的是使用FROM指令解析生成参数的事实为要复制的图像创建一个额外的别名:

ARG GIT_TOKEN=abc:1a2b3
ARG EXECUTION_ENV=local

# get dependencies from github
FROM alpine/git as gitclone-ci
WORKDIR /usr/src/
RUN git clone https://{GIT_USER_TOKEN}@github.com/something.git \
    && git clone https://{GIT_USER_TOKEN}@github.com/somethingelse.git

## in local dependencies are already available in the parent folder
FROM alpine/git as gitclone-local
WORKDIR /usr/src/
COPY ../something /usr/src/something 
COPY ../somethingelse /usr/src/somethingelse

FROM gitclone-${EXECUTION_ENV} as intermediate

FROM node:latest as builder
WORKDIR /usr/src
COPY --from=intermediate /usr/src .
COPY package* ./
COPY src/ src/
RUN ["npm", "install"]