
A
Dockerfileis a text document that contains all the commands a user could call on the command line to assemble an image.
Dockerfile的格式如下:
# Comment
INSTRUCTION arguments
# 符號後的文字視為註解,除非他是個 有效的 parser directives
# directive=value
FROM 前被使用FROM 指令開頭,(但可在 parser directives、註解、和全域的 ARGs 之後)FROM 指令定義了這個 dockerfile 使用的基礎映像 (Parent Image)(新的映像須在舊映像上進行疊加)FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]
ARG 的作用為自定義的參數,對應到docker build的指令,即是
--build-arg <varName>=<value>的部分
ENV代表環境變數的部分
環境變數可以以 $variable_name 或 ${variable_name} 標註
${variable_name} 也支援一些基本的 bash modifiers:
${variable:-word} indicates that if variable is set then the result will be that value. If variable is not set then word will be the result.${variable:+word} indicates that if variable is set then word will be the result, otherwise the result is the empty string.word can be any string, including additional environment variables.Escaping is possible by adding a \ before the variable: \$foo or \${foo}, for example, will translate to $foo and ${foo} literals respectively.
(以上來自Dockerfile reference | Docker Documentation)
WORKDIR 為 dockerfile 在容器中的工作目錄
目的是在容器尚未建立前執行命令,以完成像是建立環境等等的任務,有二種寫法
shell form, the command is run in a shell, which by default is
/bin/sh -con Linux orcmd /S /Con Windows
RUN <command>
\ 以便將一個命令隔行書寫
execform
RUN ["executable", "param1", "param2"]
RUN 運行命令時不會牽涉到殼層,因此若要執行和 shell 有關的命令時,可以使用 shell 型的 RUN 或 RUN ["/bin/bash", "-c" "..."] 指定以shell來運行RUN 指令會在當前映象上疊加一層並執行命令,且命令執行完成後的映像會接續給dockerfile中的下一步運行
RUN 還有其他的運作參數,在此就不在贅述,詳情可到[Dockerfile Reference](Dockerfile reference | Docker Documentation)查看
目的也是執行命令,但是只能出現一次,一旦出現就代表容器建立完成,後面就算有其他的指令像是 RUN 等,都會沒有作用
總共有三種寫法
CMD ["executable","param1","param2"] (exec form, this is the preferred form)
CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
CMD command param1 param2 (shell form)
CMD 的指令,若有多個 CMD 同時出現,那只有最後一個會有效果The main purpose of a
CMDis to provide defaults for an executing container
(from Dockerfile reference)
CMD 的目的是執行 container,也就是將container設定為預備好上工的狀態COPY 人如其名,就是COPY
COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]
ADD,有兩種形式,後者會在路徑中有空格時使用。
其目的是搬移資料(包含遠端URLs),遇到壓縮檔會自己解壓縮
ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]
ADD 也可以直接將 git 的 repo 加入,不需要使用 git 的指令
ADD [--keep-git-dir=<boolean>] <git ref> <dir>
--keep-git-dir=true 會將 .git 保留在目錄裡,預設為 false
LABEL的功能,就是 alias
此命令是將container的埠口開放,預設以 TCP 協定連線,也可以以 EXPOSE [port no.]/[protocol]的形式指定埠口和協定,
要注意的是,這個指令還是不會讓container開啟對外服務,仍須以 docker run 時的 -p 參數去設定通訊埠轉發,container才會真正的接收來自外部的請求。
以上是幾個比較常用到的命令,docker reference上還有很多很多的資料,有興趣的話可以上去看看喔~明天就來實際撰寫一個dockerfile吧