为 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 入门

Let's practice!

Docker 入门

Preparing Video For Download...