1 启动容器
docker run
:新建并启动容器,需要把—rm去掉,因为我们需要在退出时保存容器。docker container start -i
:直接将一个已经终止的容器启动运行,同时我们需要进入交互中断,不然什么都看不到
后台运行:如果使用了-d选项,容器会在后台以守护态运行,并且一切打印不会显示,需要用docker container logs [id]查看。
barret@blinux:~$ docker run -d ubuntu:20.04 /bin/sh -c "while true; do echo hello world; sleep 1; done"
barret@blinux:~$ docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7db684007706 ubuntu:20.04 "/bin/sh -c 'while t…" 37 seconds ago Up 36 seconds modest_wu
abf5f7a2a78b ubuntu:20.04 "bash" 9 minutes ago Exited (0) 5 minutes ago happy_haslett
barret@blinux:~$ docker container logs 7db684007706
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
2 终止容器
上面例子里,后台容器会一直运行,需要使用下面命令终止。docker container stop [id]
barret@blinux:~$ docker container stop 7db684007706
7db684007706
barret@blinux:~$ docker container ls -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7db684007706 ubuntu:20.04 "/bin/sh -c 'while t…" 3 minutes ago Exited (137) 9 seconds ago modest_wu
abf5f7a2a78b ubuntu:20.04 "bash" 12 minutes ago Exited (0) 8 minutes ago happy_haslett
对于前台交互容器,exit或Ctrl+d之后会自动停止。