自己建立 Docker 映像檔

Docker 入門

Tim Sangster

Software Engineer @ DataCamp

用 Dockerfile 建立映像檔

Dockerfiles are build to get a Docker Images which when run create a container.

Docker 入門

開始撰寫 Dockerfile

Dockerfile 一定會從另一個映像檔開始,使用 FROM 指令指定。

FROM postgres
FROM ubuntu
FROM hello-world
FROM my-custom-data-pipeline
FROM postgres:15.0
FROM ubuntu:22.04
FROM hello-world:latest
FROM my-custom-data-pipeline:v1
Docker 入門

建置 Dockerfile

建置 Dockerfile 會產生一個映像檔。

docker build /location/to/Dockerfile
docker build .
[+] Building 0.1s (5/5) FINISHED
 => [internal] load build definition from Dockerfile
 => => transferring dockerfile: 54B
...
 => CACHED [1/1] FROM docker.io/library/ubuntu
 => exporting to image
 => => exporting layers
 => => writing image sha256:a67f41b1d127160a7647b6709b3789b1e954710d96df39ccaa21..
Docker 入門

替映像檔命名

實務上我們幾乎都會用 -t 旗標替映像檔命名:

docker build -t first_image .
...
=> => writing image sha256:a67f41b1d127160a7647b6709b3789b1e954710d96df39ccaa21..
=> => naming to docker.io/library/first_image 
docker build -t first_image:v0 .
=> => writing image sha256:a67f41b1d127160a7647b6709b3789b1e954710d96df39ccaa21..
=> => naming to docker.io/library/first_image:v0
Docker 入門

自訂映像檔

RUN <valid-shell-command>
FROM ubuntu
RUN apt-get update
RUN apt-get install -y python3

使用 -y 旗標可避免互動式詢問:

...
After this operation, 22.8 MB of additional disk space will be used.
Do you want to continue? [Y/n]
Docker 入門

建置較完整的 Dockerfile

建置映像檔時,Docker 其實會執行 RUN 後的指令

Docker 執行 RUN apt-get update 所花的時間,和你自己執行一樣長!

root@host:/# apt-get update
Get:1 http://ports.ubuntu.com/ubuntu-ports jammy InRelease [270 kB]
...
Get:17 http://ports.ubuntu.com/ubuntu-ports jammy-security/restricted arm64 Pack..
Fetched 23.0 MB in 2s (12.3 MB/s)                          
Reading package lists... Done
Docker 入門

重點整理

用途 Dockerfile 指令
從映像檔開始撰寫 Dockerfile FROM <image-name>
在映像檔中加入 shell 指令 RUN <valid-shell-command>
確保 shell 指令不需使用者輸入 RUN apt-get install -y python3

用途 Shell 指令
從 Dockerfile 建置映像檔 docker build /location/to/Dockerfile
在目前工作目錄建置映像檔 docker build .
建置時指定映像檔名稱 docker build -t first_image .
Docker 入門

一起來練習吧!

Docker 入門

Preparing Video For Download...