(二)进入容器的方法

​ 我们经常需要进到容器里去做一些工作,比如查看日志、调试、启动其他进程等。有两种方法进入容器:attach 和 exec。

(1)docker attach

通过 docker attach 可以 attach 到容器启动命令的终端,例如:

root@cuiyongchao:/dockerfile# docker run -d ubuntu /bin/bash -c "while true;do sleep 1;echo this is ubuntu.;done"
d3d17f299cfc5de981ab67f34bcfa9110581fb961b49b67d7e646880cb4520c7
root@cuiyongchao:/dockerfile# docker attach d3d17f299cfc5de981ab67f34bcfa9110581fb961b49b67d7e646880cb4520c7
this is ubuntu.
this is ubuntu.

这次我们通过 “长ID” attach 到了容器的启动命令终端,之后看到的是echo 每隔一秒打印的信息。

注:可通过 Ctrl+p 然后 Ctrl+q 组合键退出 attach 终端。

(2)docker exec

通过 docker exec 进入相同的容器:

root@cuiyongchao:/dockerfile# docker run -d ubuntu /bin/bash -c "while true;do sleep 1;echo this is ubuntu.;done"
872ebb8a83c1ad210b8dc383af02c31480bb8bca70aacad1f1b971573cb290c0

root@cuiyongchao:/dockerfile# docker exec -it  872ebb8a83c1ad210b8dc383af02c31480bb8bca70aacad1f1b971573cb290c0 /bin/bash   ①
root@872ebb8a83c1:/# ②
root@872ebb8a83c1:/# ps -ef ③
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 02:42 ?        00:00:00 /bin/bash -c while true;do sleep 1;echo this is ubuntu.;done
root         53      0  0 02:43 pts/0    00:00:00 /bin/bash
root       2314      1  0 03:21 ?        00:00:00 sleep 1
root       2315     53  0 03:21 pts/0    00:00:00 ps -ef
root@872ebb8a83c1:/# exit ④
exit
root@cuiyongchao:/dockerfile# 

说明如下:

-it 以交互模式打开 pseudo-TTY,执行 bash,其结果就是打开了一个 bash 终端。

② 进入到容器中,容器的 hostname 就是其 “短ID”。

③ 可以像在普通 Linux 中一样执行命令。ps -elf 显示了容器启动进程while 以及当前的 bash 进程。

④ 执行 exit 退出容器,回到 docker host。docker exec -it <container> bash|sh 是执行 exec 最常用的方式。

(3)attach VS exec

​ attach 与 exec 主要区别如下:

  1. attach 直接进入容器 启动命令 的终端,不会启动新的进程。
  2. exec 则是在容器中打开新的终端,并且可以启动新的进程。
  3. 如果想直接在终端中查看启动命令的输出,用 attach;其他情况使用 exec。

当然,如果只是为了查看启动命令的输出,可以使用 docker logs 命令:

root@cuiyongchao:/dockerfile# docker logs -f d3d17f299cfc5de981ab67f34bcfa9110581fb961b49b67d7e646880cb4520c7
this is ubuntu.
this is ubuntu.
this is ubuntu.

-f 的作用与 tail -f 类似,能够持续打印输出。

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/cuiyongchao007/p/13955364.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!