(二)進入容器的方法
? 我們經常需要進到容器里去做一些作業,比如查看日志、除錯、啟動其他行程等,有兩種方法進入容器: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 主要區別如下:
- attach 直接進入容器 啟動命令 的終端,不會啟動新的行程,
- exec 則是在容器中打開新的終端,并且可以啟動新的行程,
- 如果想直接在終端中查看啟動命令的輸出,用 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.uj5u.com/qita/209891.html
標籤:其他
上一篇:容器(四) 運行容器方法【17】
下一篇:計算機組成原理復習
