Docker的Dockerfile是用來建構docker images的指令檔。
Dockerfile是由Dockerfile指令組成的文字檔。可在Docker CLI使用docker build執行Dockerfile來建構docker image。
docker build會透過Dockerfile及build context來建構docker image。build context為PATH或URL路徑的檔案及子目錄中的檔案。PATH為檔案系統目錄,URL為Git repository。
例如docker build /docker/mycontext使用檔案系統根目錄下的/docker/mycontext目錄為build context。
$ docker build /docker/mycontext
docker build https://github.com/user/app.git#demo:docker使用git repository https://github.com/user/app.git分支demo下的docker目錄為build context。
$ docker build https://github.com/user/app.git#demo:docker
docker build是由Docker daemon執行,而非Docker CLI(也就是操作docker指令的地方)。build時Docker會將build context的檔案送到daemon,因為build過程中需要參考build context中的檔案來建構image。通常會把Dockerfile放在build context的目錄中,並在該目錄執行docker build確保build context僅限於該目錄中的檔案。
注意不要將build context設為檔案系統根目錄/,否則build會將整個根目錄及下面所有的子目錄及檔案都送到Docker daemon。
下面示範在macOS建構一個以centos 7為base image,並在上面執行shell script檔的docker image。
範例環境:
- macOS Catalina
- Docker 19.03.12
在~/Document新建一個目錄temp,此即為待會docker build使用的build context。
在~/Document/temp新增一個script.sh內容如下。此檔案為執行Dockerfile時要搬移到image並被執行的shell script檔。
script.sh
#!/bin/bash
echo hello world
在~/Document/temp目錄新增一個文字檔命名為Dockerfile且不用副檔名內容如下。此即為docker build使用的Dockerfile。
Dockerfile
FROM centos:7
COPY script.sh /tmp/script.sh
RUN ls tmp
RUN ./tmp/script.sh
Dockerfile中必須以FROM開頭,用來指定container的base image,這邊以centos:7為base image。
COPY用來將build context中的script.sh複製到container檔案目錄下的/tmp/script.sh。
RUN用來執行container的shell指令。首先使用ls tmp列出根目錄下的tmp目錄中的檔案,然後執行tmp目錄下的script.sh。script.sh即為上一步COPY從build context複製的script.sh。
所以目前~/Document/temp下有兩個檔案,分別為script.sh及Dockerfile。
~/Documents/temp$ ls
Dockerfile script.sh
在~/Document/temp執行docker build -t script .以當前目錄的Dockerfile建構image,image名稱為script。-t用來指定image名稱;PATH設為.即以當前目錄為build context。
~/Documents/temp$ docker build -t script .
Sending build context to Docker daemon 12.29kB
Step 1/4 : FROM centos:7
---> 8652b9f0cb4c
Step 2/4 : COPY script.sh /tmp/script.sh
---> ddce844d637b
Step 3/4 : RUN ls tmp
---> Running in 19a866dab496
ks-script-DrRL8A
script.sh
yum.log
Removing intermediate container 19a866dab496
---> 3b5e270fe3a7
Step 4/4 : RUN ./tmp/script.sh
---> Running in 290c5040a113
hello world
Removing intermediate container 290c5040a113
---> ebd440515a3e
Successfully built ebd440515a3e
Successfully tagged script:latest
從以上可看到Dockerfile每一步命令的執行結果。
使用docker images列出本機docker registry的images,即可見到建構好的script images。
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
script latest ebd440515a3e 2 minutes ago 204MB
輸入docker run -it --name script script來執行image script並以--name將container命名為script且以-it在啟動後進入container的bash shell。
$ docker run -it --name script script
[root@8b429764e4d2 /]#
在container shell輸入ls tmp檢視可看到script.sh。
[root@8b429764e4d2 /]# ls tmp
ks-script-DrRL8A script.sh yum.log
沒有留言:
張貼留言