如何在宿主機上執行容器里的jmap,jtack,jstat 命令獲取信息(原創)


一般情況下,我們要獲取docker容器里的jvm信息只能進入容器后執行jmap,jstack,jstat 命令去獲取,jstack,jstat還好,但是jmap dump的文件要拿出來,得先copy dump文件到掛載在宿主機上的目錄,或者使用docker cp命令去獲取,

如  https://pathtogeek.com/thread-heap-dumps-from-a-docker-container

1. Run the below command to bash into the container. Please change the CONTAINER_NAME appropriately

 

      docker exec -it CONTAINER_NAME bash
    

2. Then type jps to find the all the Java application details and extract the PID for your application

 

    jps
  

3. Then run the below command to get the thread dump. Please change the PID appropriately

 

     jstack PID > threadDump.tdump 
     

4. Then run the below command to get the Heap dump. Please change the PID appropriately

 

        jmap -dump:live,format=b,file=heapDump.hprof PID 
     

5. Then exit from the docker container and download the threadDump.tdump and heapDump.hprof from the docker container by running the below command. Please change the CONTAINER_NAME appropriately

 

      sudo docker cp CONTAINER_NAME:threadDump.tdump .
      sudo docker cp CONTAINER_NAME:heapDump.hprof .
    

現在我們要在宿主機上直接獲取這些信息要怎么做的,

docker exec -it $containerid /bin/ps x  獲取到我們需要的容器里的進程id

   docker exec -it $containerid /jdk/bin/jstack $pid   獲取容器里進程的jstack信息

   一切執行順利,我們繼續試試jmap

   docker exec -it $containerid /jdk/bin/jmap -dump:live,format=b,file=heapDump.hprof $pid

報錯

  why? 網上有篇文章提及了類似的情況 https://www.xiaocaicai.com/2018/07/09/docker-%E5%AE%B9%E5%99%A8%E9%87%8C%E6%97%A0%E6%B3%95%E4%BD%BF%E7%94%A8-jdk-%E7%9A%84-jmap-%E7%AD%89%E5%91%BD%E4%BB%A4%E7%9A%84%E9%97%AE%E9%A2%98/

線上java程序出現異常,需要打印內存信息進行debug,發現沒有 jmap,jstack等工具。
發現容器基礎鏡像選擇的是FROM java:8-jre,jre環境是不包含這類工具的,遂將換成FROM java:8,這類工具便包含在內了。
使用時發現還是不能使用,出現錯誤 “Can’t attach to the process: ptrace(PTRACE_ATTACH, ..) failed for 1: Operation not permitted docker”

查詢資料后發現:
這其實不是什么 Bug,而是 Docker 自 1.10 版本開始加入的安全特性。
類似於 jmap 這些 JDK 工具依賴於 Linux 的 PTRACE_ATTACH,而是 Docker 自 1.10 在默認的 seccomp 配置文件中禁用了 ptrace。
相關資料

主要方法2個:
1.使用 –cap-add 明確添加指定功能:
docker run –cap-add=SYS_PTRACE …

2.Docker Compose 自 version 1.1.0 (2015-02-25) 起支持 cap_add。

version: '2'

services:
  mysql:
    ...
  api:
    ...
    cap_add:
      - SYS_PTRACE

那就死馬當活馬醫把,修改marathon的配置

 

執行ps x|grep docker|grep web,  看到docker run命令里已經有 cap-add 這個參數了

再次執行,成功導出

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM