1 启动容器

  • docker run:新建并启动容器,需要把—rm去掉,因为我们需要在退出时保存容器。
  • docker container start -i:直接将一个已经终止的容器启动运行,同时我们需要进入交互中断,不然什么都看不到

后台运行:如果使用了-d选项,容器会在后台以守护态运行,并且一切打印不会显示,需要用docker container logs [id]查看。

  1. barret@blinux:~$ docker run -d ubuntu:20.04 /bin/sh -c "while true; do echo hello world; sleep 1; done"
  2. barret@blinux:~$ docker container ls -a
  3. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  4. 7db684007706 ubuntu:20.04 "/bin/sh -c 'while t…" 37 seconds ago Up 36 seconds modest_wu
  5. abf5f7a2a78b ubuntu:20.04 "bash" 9 minutes ago Exited (0) 5 minutes ago happy_haslett
  6. barret@blinux:~$ docker container logs 7db684007706
  7. hello world
  8. hello world
  9. hello world
  10. hello world
  11. hello world
  12. hello world
  13. hello world
  14. hello world
  15. hello world

2 终止容器

上面例子里,后台容器会一直运行,需要使用下面命令终止。
docker container stop [id]

  1. barret@blinux:~$ docker container stop 7db684007706
  2. 7db684007706
  3. barret@blinux:~$ docker container ls -a
  4. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  5. 7db684007706 ubuntu:20.04 "/bin/sh -c 'while t…" 3 minutes ago Exited (137) 9 seconds ago modest_wu
  6. abf5f7a2a78b ubuntu:20.04 "bash" 12 minutes ago Exited (0) 8 minutes ago happy_haslett

对于前台交互容器,exitCtrl+d之后会自动停止。