為你的 Docker 映像選擇啟動指令

Docker 入門

Tim Sangster

Software Engineer @ DataCamp

什麼是啟動指令?

hello-world 映像會印出文字後停止。

docker run hello-world
Hello from Docker!

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon created a new container from the hello-world image which runs the
    executable that produces the output you are currently reading.
  3. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.
Docker 入門

什麼是啟動指令?

含有 python 的映像可在啟動時直接開啟 python。

docker run python3-sandbox
Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
...
....
>>> exit()
repl@host:/#
Docker 入門

在啟動時執行 shell 指令

CMD <shell-command>

CMD 指令:

  • 影像啟動時執行。
  • 不會增加映像大小。
  • 不會增加建置時間。
  • 若設定多次,只有最後一個生效。
Docker 入門

典型用法

啟動應用程式以執行工作流程,或接受外部連線。

CMD python3 my_pipeline.py
CMD postgres

啟動一個腳本,再由它啟動多個應用程式

CMD start.sh
CMD python3 start_pipeline.py
Docker 入門

什麼時候會停止?

$$

  • hello-world 映像 -> 印完文字後
  • 資料庫映像 -> 當資料庫結束時

$$

越通用的映像需要越通用的啟動指令。

  • Ubuntu 映像 -> 關閉 shell 時
Docker 入門

覆寫預設啟動指令

啟動映像

docker run <image>

以自訂啟動指令啟動映像

docker run <image> <shell-command>

互動式啟動映像並使用自訂啟動指令

docker run -it <image> <shell-command>
docker run -it ubuntu bash
Docker 入門

重點整理

用途 Dockerfile 指令
在由映像啟動的容器中加入要執行的 shell 指令。 CMD <shell-command>

用途 Shell 指令
覆寫映像中的 CMD docker run <image> <shell-command>
覆寫映像中的 CMD,並以互動式執行 docker run -it <image> <shell-command>
Docker 入門

一起來練習吧!

Docker 入門

Preparing Video For Download...