Dockerfile (1) - Detailed explanation of FROM instruction

FROM

  • Indicates which image the current image is based on
  • A dockerfile must start with FROM, except that ARG commands can precede FROM
FROM [--platform=<platform>] <image> [AS <name>]

FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]

FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]

small chestnut

FROM alpine:latest

A dockerfile can have multiple FROMs

  • There can be multiple FROMs to create multiple mirrors, or to differentiate build phases, and use one build phase as a dependency of another build phase
  • AS <name> is to name the current build phase
  • In the subsequent construction phase, it can be used for the FROM and COPY instructions, by referencing the previously constructed image

--from=<name>

# 第一构建阶段:将仅用于生成 requirements.txt 文件
FROM tiangolo/uvicorn-gunicorn:python3.9 as requirements-stage

# 将当前工作目录设置为 /tmp
WORKDIR /tmp

# 生成 requirements.txt
RUN touch requirements.txt

# 第二构建阶段,在这往后的任何内容都将保留在最终容器映像中
FROM python:3.9

# 将当前工作目录设置为 /code
WORKDIR /code

# 复制 requirements.txt;这个文件只存在于前一个 Docker 阶段,这就是使用 --from-requirements-stage 复制它的原因
COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt

# 运行命令
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

# 复制
COPY ./app /code/app

Understand how ARG and FROM interact

The FROM directive supports variables declared by any ARG directive that appears before the first FROM

ARG  CODE_VERSION=latest
FROM base:${CODE_VERSION}
CMD  /code/run-app

FROM extras:${CODE_VERSION}
CMD  /code/run-extras

Notice

  • ARGs declared before FROM are outside the build phase and thus cannot be used in any instruction after FROM
  • To use the default value of an ARG declared before the first FROM, declare an ARG directive with no value once within the build phase
ARG VERSION=latest
FROM busybox:$VERSION
ARG VERSION
RUN echo $VERSION > image_version

Guess you like

Origin blog.csdn.net/NHB456789/article/details/130888609