参考https://www.cnblogs.com/CloudMan6/p/6928772.html
我们经常需要进到容器里面去做一些工作,比如查看日志、调试、启动其他进程等。
有两种进入容器的方法 attach 和 exec
docker attach
使用快捷键 CTRL + P + Q 退出,但是不会结束容器(不加 -it 该快捷键无效)
不要使用 CTRL + C 强行退出,这样会导致容器停止
[email protected]:~# docker run -d -it busybox ping 127.0.0.1
6a5bf51cba2e34da3c464cd90ec4c96d94728dab3500420763f0e197a54e827f
[email protected]:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6a5bf51cba2e busybox "ping 127.0.0.1" 6 seconds ago Up 5 seconds epic_kilby
[email protected]:~# docker attach 6a5bf51cba2e34da3c464cd90ec4c96d94728dab3500420763f0e197a54e827f
64 bytes from 127.0.0.1: seq=20 ttl=64 time=0.048 ms
64 bytes from 127.0.0.1: seq=21 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: seq=22 ttl=64 time=0.059 ms
64 bytes from 127.0.0.1: seq=23 ttl=64 time=0.062 ms
read escape sequence [ CTRL + P + Q ]
[email protected]:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6a5bf51cba2e busybox "ping 127.0.0.1" 4 minutes ago Up 4 minutes epic_kilby
docker exec
-it 会先建一个bash终端,用完之后执行exit退出即可,但不会关闭容器
[email protected]:~# docker exec -it 6a5bf51cba2e sh
/ # w
USER TTY IDLE TIME HOST
/ # ps -ef | grep ping
1 root 0:00 ping 127.0.0.1
/ # exit
[email protected]:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6a5bf51cba2e busybox "ping 127.0.0.1" About an hour ago Up About an hour epic_kilby
attach VS exec
1、attach直接进入容器启动命令的终端,不会启动新的终端,所以进入容器后可以直接看到ping的内容
2、exec则是在容器中新开一个终端并且可以启动新的进程
3、查看容器启动命令的输出使用attach,其他情况使用exec
docker logs
docker logs -f ID 有类似tail -f 的效果,持续在屏幕上打印启动命令的结果
[email protected]:~# docker logs 6a5bf51cba2e | head
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: seq=0 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: seq=1 ttl=64 time=0.057 ms
64 bytes from 127.0.0.1: seq=2 ttl=64 time=0.048 ms
64 bytes from 127.0.0.1: seq=3 ttl=64 time=0.055 ms
64 bytes from 127.0.0.1: seq=4 ttl=64 time=0.057 ms
64 bytes from 127.0.0.1: seq=5 ttl=64 time=0.055 ms
64 bytes from 127.0.0.1: seq=6 ttl=64 time=0.054 ms
64 bytes from 127.0.0.1: seq=7 ttl=64 time=0.051 ms
64 bytes from 127.0.0.1: seq=8 ttl=64 time=0.049 ms
end
原文地址:https://www.cnblogs.com/www1707/p/10280085.html