Docker image 與 container 的建構流程

其實這張圖已經解說很清楚了

ARG

這裡有個 Dockerfile 範例如下 :

1
2
3
4
5
6
7
ARG VERSION="latest"

FROM alpine:${VERSION}

ARG VERSION

RUN echo "alpine:${VERSION}" > /tmp/os_version
  • VERSION 設定預設值 latest
  • 若在 FROM 執行之後,還要使用剛剛 ARG VERSION 變數的話,則還需要再宣告一次,否則會找不到ARG變數

When building a docker image, you can overwrite ARG by using -–build-arg:

1
$ docker build --build-arg VERSION=arg1_value

In docker-compose.yml file, it will look like :

1
2
3
4
5
6
7
8
version: '3'

services:
  service1:
    build:
      context: ./dir-with-docker-compose
      args:
        arg1: arg1_value

ENV

When running a dokcer container, you can overwrite ENV by using -e :

1
$ docker run -e "env1=env1_value" alpine env

In Dockerfile, it will look like :

1
2
3
ENV VAR1 "Hello world"

RUN echo ${VAR1} > /tmp/demo

In docker-compose.yml file, it will look like :

1
2
3
4
5
6
7
version: '3'

services:
  demo_alpine:
    image: alpine
      environment: 
        - env1=env1_value

Additionally, you can also use env-file to set massive envs :

demo_env.env

1
2
3
4
5
env1=env1_value
env2=env2_value
env3=env3_value
env4=env4_value
env5=env5_value
1
$ docker run --env-file=demo_env.env alpine env
1
2
3
4
5
6
version: '3'

services:
  demo_alpine:
    image: alpine
      env_file: demo_env.env

當一起混合使用會發生什麼事 ?

舉一個例子

1
2
3
4
5
6
FROM alpine

ARG VAR1="Hello world"
ENV VAR1 ${VAR1}

RUN echo ${VAR1} > /tmp/demo

Building image…

1
$ docker build -t="demo-alpine" .

case 1

1
2
3
4
$ docker run -e "VAR1=Hello Scott" demo-alpine env
HOSTNAME=f13f27da2cae
VAR1=Hello Scott
HOME=/root

列出環境變數,可透過 ENV 指定 VAR1 ,但 ARG 是不行的

case 2

1
2
$ docker run -e "VAR1=Hello Scott" demo-alpine cat /tmp/demo
Hello world

在 Build image 階段,已經將 ARG 的值填入 /tmp/demo ,所以才會印出 Hello world

Conclusion

See different ?

  • We use ARG in building images stage
  • We use ENV in runngin containers stage

That’s it !

Reference

  1. Docker ARG, ENV and .env - a Complete Guide