构建参数和环境变量 (ARG vs ENV)

ARGENV 是经常容易被混淆的两个Dockerfile的语法,都可以用来设置一个“变量”。 但实际上两者有很多的不同。

  1. FROM ubuntu:20.04
  2. RUN apt-get update && \
  3. apt-get install -y wget && \
  4. wget https://github.com/ipinfo/cli/releases/download/ipinfo-2.0.1/ipinfo_2.0.1_linux_amd64.tar.gz && \
  5. tar zxf ipinfo_2.0.1_linux_amd64.tar.gz && \
  6. mv ipinfo_2.0.1_linux_amd64 /usr/bin/ipinfo && \
  7. rm -rf ipinfo_2.0.1_linux_amd64.tar.gz

ENV

  1. FROM ubuntu:20.04
  2. ENV VERSION=2.0.1
  3. RUN apt-get update && \
  4. apt-get install -y wget && \
  5. wget https://github.com/ipinfo/cli/releases/download/ipinfo-${VERSION}/ipinfo_${VERSION}_linux_amd64.tar.gz && \
  6. tar zxf ipinfo_${VERSION}_linux_amd64.tar.gz && \
  7. mv ipinfo_${VERSION}_linux_amd64 /usr/bin/ipinfo && \
  8. rm -rf ipinfo_${VERSION}_linux_amd64.tar.gz

ARG

  1. FROM ubuntu:20.04
  2. ARG VERSION=2.0.1
  3. RUN apt-get update && \
  4. apt-get install -y wget && \
  5. wget https://github.com/ipinfo/cli/releases/download/ipinfo-${VERSION}/ipinfo_${VERSION}_linux_amd64.tar.gz && \
  6. tar zxf ipinfo_${VERSION}_linux_amd64.tar.gz && \
  7. mv ipinfo_${VERSION}_linux_amd64 /usr/bin/ipinfo && \
  8. rm -rf ipinfo_${VERSION}_linux_amd64.tar.gz

区别

docker-image

ARG 可以在镜像build的时候动态修改value, 通过 --build-arg

  1. $ docker image build -f .\Dockerfile-arg -t ipinfo-arg-2.0.0 --build-arg VERSION=2.0.0 .
  2. $ docker image ls
  3. REPOSITORY TAG IMAGE ID CREATED SIZE
  4. ipinfo-arg-2.0.0 latest 0d9c964947e2 6 seconds ago 124MB
  5. $ docker container run -it ipinfo-arg-2.0.0
  6. root@b64285579756:/#
  7. root@b64285579756:/# ipinfo version
  8. 2.0.0
  9. root@b64285579756:/#

ENV 设置的变量可以在Image中保持,并在容器中的环境变量里