运行 Docker 容器

Docker 入门

Tim Sangster

Software Engineer @ DataCamp

先决条件

命令 用途
nano <file-name> 在 nano 文本编辑器中打开 <file-name>
touch <file-name> 创建指定名称的空文件
echo "<text>" 将 <text> 输出到控制台
<command> >> <file> 将 <command> 的输出追加到 <file> 末尾
<command> -y 对 <command> 的所有提示自动回答 yes
Docker 入门

Docker CLI

  • Docker 命令行界面会向 Docker 守护进程发送指令。
  • 每个命令都以 docker 开头。

名为 Ubuntu 的镜像(完整 Ubuntu OS 安装)可启动为正在运行的 Ubuntu OS,我们可通过 shell 与之交互。

Docker 入门

Docker 容器输出

docker run <image-name>
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 入门

选择 Docker 容器输出

docker run <image-name>
docker run ubuntu
repl@host:/# docker run ubuntu

repl@host:/#
Docker 入门

交互式 Docker 容器

docker run 中添加 -it 可在启动的容器中获得交互式 shell。

docker run -it <image-name>
docker run -it ubuntu
docker run -it ubuntu
repl@container:/#
repl@container:/# exit
exit
repl@host:/#
Docker 入门

以分离模式运行容器

docker run 中添加 -d 可在后台运行容器,并将 Shell 控制权返还给我们。

docker run -d <image-name>
docker run -d postgres
repl@host:/# docker run -d postgres
4957362b5fb7019b56470a99f52218e698b85775af31da01958bab198a32b072
repl@host:/#
Docker 入门

列出并停止运行中的容器

docker ps
repl@host:/# docker ps
CONTAINER ID   IMAGE      COMMAND                  CREATED  
4957362b5fb7   postgres   "docker-entrypoint.s…"   About a minute ago
STATUS              PORTS      NAMES
Up About a minute   5432/tcp   awesome_curie
docker stop <container-id>
repl@host:/# docker stop cf91547fd657
cf91547fd657
Docker 入门

新命令总结

用途 命令
启动容器 docker run <image-name>
启动交互式容器 docker run -it <image-name>
启动分离式容器 docker run -d <image-name>
列出运行中容器 docker ps
停止容器 docker stop <container-id>
Docker 入门

让我们来练习!

Docker 入门

Preparing Video For Download...