Docker 中的 .NET 異常了怎么抓 Dump|當前獨家
有很多朋友跟我說,在 Windows 上看過你文章知道了怎么抓 Crash, CPU爆高,內存暴漲 等各種Dump,為什么你沒有寫在 Docker 中如何抓的相關文章呢?瞧不上嗎?
(相關資料圖)
哈哈,在DUMP的分析旅程中,跑在 Docker 中的 .NET 占比真的不多,大概10個dump有 1-2 個是 docker 中的,市場決定了我的研究方向,為了彌補這一塊的空洞,決定寫一篇文章來分享下這三大異常下的捕獲吧。
二:Docker 下的三大異常捕獲1. crash dump 捕獲前不久我寫了一篇 Linux 上的 .NET 崩潰了怎么抓 Dump (https://www.cnblogs.com/huangxincheng/p/17440153.html)
的文章,使用了微軟推薦的環境變量方式,其實這在 Docker 中是一樣適用的。
為了讓 webapi
崩潰退出,我故意造一個棧溢出異常,參考代碼如下:
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthorization(); //1. crash Task.Factory.StartNew(() => { Test("a"); }); app.Run(); } public static string Test(string a) { return Test("a" + a.Length); } }
有了代碼之后,接下來寫一個 Dockerfile,主要就是把三個環境變量
塞進去。
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtimeWORKDIR /appCOPY ./ ./# 1. 使用中科大鏡像源RUN sed -i "s/deb.debian.org/mirrors.ustc.edu.cn/g" /etc/apt/sources.listENV COMPlus_DbgMiniDumpType 4ENV COMPlus_DbgMiniDumpName /dumps/%p-%e-%h-%t.dmpENV COMPlus_DbgEnableMiniDump 1ENTRYPOINT ["dotnet", "AspNetWebApi.dll"]
這里有一個細節,為了能夠讓 Docker 中的 webapi 能夠訪問到,將 localhost 設置為 * ,修改 appsettings.json
如下:
{ "urls": "http://*:5001", "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*"}
有了這些基礎最后就是 docker build & docker run 啦。
[root@localhost data]# docker build -t aspnetapp .[+] Building 0.3s (9/9) FINISHED => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 447B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:6.0 0.3s => [1/4] FROM mcr.microsoft.com/dotnet/aspnet:6.0@sha256:a2a04325fdb2a871e964c89318921f82f6435b54 0.0s => [internal] load build context 0.0s => => transferring context: 860B 0.0s => CACHED [2/4] WORKDIR /app 0.0s => CACHED [3/4] COPY ./ ./ 0.0s => CACHED [4/4] RUN sed -i "s/deb.debian.org/mirrors.ustc.edu.cn/g" /etc/apt/sources.list 0.0s => exporting to image 0.0s => => exporting layers 0.0s => => writing image sha256:be69203995c0e5423b2af913549e618d7ee8306fff3961118ff403b1359ae571 0.0s => => naming to docker.io/library/aspnetapp 0.0s[root@localhost data]# docker run -itd -p 5001:5001 --privileged -v /data2:/dumps --name aspnetcore_sample aspnetappca34c9274d998096f8562cbef3a43a7cbd9aa5ff2923e0f3e702b159e0b2f447[root@localhost data]# docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESca34c9274d99 aspnetapp "dotnet AspNetWebApi…" 20 seconds ago Exited (139) 9 seconds ago aspnetcore_sample[root@localhost data]# docker logs ca34c9274d99 ... at AspNetWebApi.Program.Test(System.String) at AspNetWebApi.Program.Test(System.String) at AspNetWebApi.Program.Test(System.String) at AspNetWebApi.Program.Test(System.String) at AspNetWebApi.Program+<>c.b__0_0() at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task+<>c.<.cctor>b__272_0(System.Object) at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread, System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef, System.Threading.Thread) at System.Threading.Tasks.Task.ExecuteEntryUnsafe(System.Threading.Thread) at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart() at System.Threading.Thread.StartCallback()[createdump] Gathering state for process 1 dotnet[createdump] Crashing thread 0017 signal 6 (0006)[createdump] Writing full dump to file /dumps/1-dotnet-ca34c9274d99-1687746929.dmp[createdump] Written 261320704 bytes (63799 pages) to core file[createdump] Target process is alive[createdump] Dump successfully written[root@localhost data2]# cd /data2[root@localhost data2]# ls -lntotal 255288-rw-------. 1 0 0 261414912 Jun 26 10:35 1-dotnet-ca34c9274d99-1687746929.dmp
上面的腳本已經寫的非常清楚了,這里有幾個注意點提一下:
--privileged一定要加上特殊權限,否則生成 dump 的時候會提示無權限。
-v /data2:/dumps防止dump丟失,記得掛載到宿主機目錄 或者 共享容器 中。
2. 內存暴漲 dump 捕獲要想對 docker 中的 .NET 程序內存 進行監控,我一直都是極力推薦 procdump
,目前最新的是版本是 1.5
, github官網地址: https://github.com/Sysinternals/ProcDump-for-Linux 鑒于現在訪問 github 太慢,大家可以把 procdump_1.5-16239_amd64.deb
下載到本地,為什么下載它,是因為容器中是 debain 系統。
下載好了之后放到項目中,使用默認代碼骨架:
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthorization(); app.Run(); } }
接下來就是寫 dockerfile 了,這里有一個細節,就是如何在 Docker 中開啟多進程,這里用 start.sh 腳本的方式開啟,參考代碼如下:
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtimeWORKDIR /appCOPY ./ ./# 1. 使用中科大鏡像源RUN sed -i "s/deb.debian.org/mirrors.ustc.edu.cn/g" /etc/apt/sources.list# 2. 安裝 gdb & procdumpRUN apt-get update && apt-get install -y gdbRUN dpkg -i procdump.debRUN echo "#!/bin/bash \n\procdump -m 30 -w dotnet /dumps & \n\dotnet \$1 \n\" > ./start.shRUN chmod +x ./start.shENTRYPOINT ["./start.sh", "AspNetWebApi.dll"]
有了這些設置后,接下來就是 publish 代碼用 docker 構建啦,為了方便演示,這里就用 前臺模式
開啟了哈。
[root@localhost data]# docker build -t aspnetapp .[+] Building 11.5s (13/13) FINISHED [root@localhost data]# docker rm -f aspnetcore_sampleaspnetcore_sample[root@localhost data]# docker run -it --rm -p 5001:5001 --privileged -v /data2:/dumps --name aspnetcore_sample aspnetappProcDump v1.5 - Sysinternals process dump utilityCopyright (C) 2023 Microsoft Corporation. All rights reserved. Licensed under the MIT license.Mark Russinovich, Mario Hewardt, John Salem, Javid HabibiSysinternals - www.sysinternals.comMonitors one or more processes and writes a core dump file when the processes exceeds thespecified criteria.[02:57:34 - INFO]: Waiting for processes "dotnet" to launch[02:57:34 - INFO]: Press Ctrl-C to end monitoring without terminating the process(es).Process Name: dotnetCPU Threshold: n/aCommit Threshold: >=30 MBThread Threshold: n/aFile Descriptor Threshold: n/aSignal: n/aException monitor OffPolling Interval (ms): 1000Threshold (s): 10Number of Dumps: 1Output directory: /dumps[02:57:34 - INFO]: Starting monitor for process dotnet (9)info: Microsoft.Hosting.Lifetime[14] Now listening on: http://[::]:5001info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.info: Microsoft.Hosting.Lifetime[0] Hosting environment: Productioninfo: Microsoft.Hosting.Lifetime[0] Content root path: /app/[02:57:35 - INFO]: Trigger: Commit usage:48MB on process ID: 9[createdump] Gathering state for process 9 dotnet[createdump] Writing full dump to file /dumps/dotnet_commit_2023-06-26_02:57:35.9[createdump] Written 254459904 bytes (62124 pages) to core file[createdump] Target process is alive[createdump] Dump successfully written[02:57:35 - INFO]: Core dump 0 generated: /dumps/dotnet_commit_2023-06-26_02:57:35.9[02:57:36 - INFO]: Stopping monitors for process: dotnet (9)[root@localhost data2]# ls -lhtotal 243M-rw-------. 1 root root 243M Jun 26 10:57 dotnet_commit_2023-06-26_02:57:35.9
從腳本信息看,當內存到了 48MB
的時候觸發的 dump 生成,也成功的進入了 /dumps
目錄中,太棒了。
抓 cpu 爆高的dump最好的方式就是多抓幾個,比如說:當 CPU >20% 連續超過 5s 抓 2個dump,這種方式抓的dump很容易就能找到真兇,為了方便演示,讓兩個 cpu 直接打滿,參考代碼如下:
public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthorization(); //3. cpu app.MapGet("/cpu", (HttpContext httpContext) => { Task.Factory.StartNew(() => { bool b = true; while (true) { b = !b; } }); Task.Factory.StartNew(() => { bool b = true; while (true) { b = !b; } }); return new WeatherForecast(); }); app.Run(); }
接下來就是修改 dockerfile,因為我的虛擬機是 8 核心,如果兩個核心被打滿,那應該會占用大概 24% 的 cpu 利用率,所以腳本中就設置 20% 吧。
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtimeWORKDIR /appCOPY ./ ./# 1. 使用中科大鏡像源RUN sed -i "s/deb.debian.org/mirrors.ustc.edu.cn/g" /etc/apt/sources.list# 2. 安裝 wgetRUN apt-get update && apt-get install -y gdbRUN dpkg -i procdump.debRUN echo "#!/bin/bash \n\procdump -c 20 -n 2 -s 5 -w dotnet /dumps & \n\dotnet \$1 \n\" > ./start.shRUN chmod +x ./start.shENTRYPOINT ["./start.sh", "AspNetWebApi.dll"]
最后就是 docker 構建。
[root@localhost data]# docker build -t aspnetapp .[+] Building 0.4s (13/13) FINISHED[root@localhost data]# docker run -it --rm -p 5001:5001 --privileged -v /data2:/dumps --name aspnetcore_sample aspnetappProcDump v1.5 - Sysinternals process dump utilityCopyright (C) 2023 Microsoft Corporation. All rights reserved. Licensed under the MIT license.Mark Russinovich, Mario Hewardt, John Salem, Javid HabibiSysinternals - www.sysinternals.comMonitors one or more processes and writes a core dump file when the processes exceeds thespecified criteria.[03:35:56 - INFO]: Waiting for processes "dotnet" to launch[03:35:56 - INFO]: Press Ctrl-C to end monitoring without terminating the process(es).Process Name: dotnetCPU Threshold: >= 20%Commit Threshold: n/aThread Threshold: n/aFile Descriptor Threshold: n/aSignal: n/aException monitor OffPolling Interval (ms): 1000Threshold (s): 5Number of Dumps: 2Output directory: /dumps[03:35:56 - INFO]: Starting monitor for process dotnet (8)info: Microsoft.Hosting.Lifetime[14] Now listening on: http://[::]:5001info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.info: Microsoft.Hosting.Lifetime[0] Hosting environment: Productioninfo: Microsoft.Hosting.Lifetime[0] Content root path: /app/
看輸出是正在監控,接下來我們訪問下網址: http://192.168.17.129:5001/cpu
,稍等片刻之后就會生成兩個dump 文件。
雖然Docker中的 .NET 程序占比較少,但把經驗總結出來還是很值得的,以后有人問怎么抓,可以把這篇文章直接丟過去啦!
關鍵詞:
您可能也感興趣:
為您推薦
焦點日報:懷進鵬為教育部直屬機關全體黨員干部講專題黨課
蔡徐坤商業版圖盤點 蔡徐坤 C女士打胎
理財產品“踩剎車”?債市不具備大跌的基礎
排行
最近更新
- Docker 中的 .NET 異常了怎么抓 Dump|當前獨家
- 拔火罐的好處和壞處有哪些?正常拔罐幾天一次最好?
- 全球信息:適合小學生看的英語動畫片_適合小學生看的動畫片
- 國家疾控局等11部門發布方案,加快實現消除血吸蟲病-世界最資訊
- 世界球精選!夏日限時美景|綠色山脈與潞黨參相映成趣
- 小圓鏡有什么危害(后視鏡小圓鏡有害處嗎?)-環球快訊
- 醫渡科技(02158)糖尿病數字療法產品通過FDA審批 當前快看
- 我在鄭州拍文物|路標_全球新消息
- 最新工資價位表來了!你是什么段位?
- 315曝光玉蕾橄欖菜環保違法被罰33萬 玉蕾橄欖菜公司已被罰沒數百萬
- 袁瀟洋:虛擬電廠將轉變電力調度的機制從而提升電網韌性_環球...
- 海關總署:我國毒情形勢持續改善 2022年海關查獲各類毒品5.3噸
- 氣溫攀升,儲能如何助力“降峰”-每日熱門
- LOTTO 非常值得關注的鞋子品牌
- 環球實時:高血壓患者可以吃辣椒嗎?無論可不可以,另外這3種...
- 環球訊息:「港股異動」李寧(02331.HK)跌3.03%
- 公安部公布六起非法占用耕地犯罪典型案例
- 綻放指間的工藝,在一鏨一刻中傳承畬族銀器之美|天天微資訊
- 最高檢披露麻醉藥品、精神藥品失管涉毒問題多發原因
- 當前熱文:甘肅酒泉一餐飲店高壓鍋爆炸致2傷
- 仰臥起坐能減掉肚子上的贅肉嗎?肚子抽脂肪多少錢一次?
- 世界最新:第四屆中國賀州國際石材·碳酸鈣展覽會即將啟幕
- 每日簡訊:鐵路端午小長假運輸發送旅客7037.9萬人次
- “瓦格納”沒有牽動金融市場神經?華爾街:情況不明,后市未定
- iPhone 15至少漲價2000 變化巨大
- 魅族20 PRO 無界版不僅僅為了提升設計這么簡單 | 吳佩頻道
- 天天快消息!曾風靡全國,如今卻被螺螄粉吊打:紅極一時的“...
- 「港股異動」康方生物(09926.HK)漲4.66%_環球要聞
- 從端午產業“三變”看消費市場活力
- 尋子22年的“雷公”,與兒子DNA復核成功!-消息