前言
学习nginx最好的方式是阅读源代码跟调试,本文介绍的是在Visual Studio Code调试Nginx,首先感谢Microsoft推出免费好用的VS code,真的很赞;
编译Nginx
- 详细编译:https://www.jianshu.com/p/82ba1b335abf
- 修改编参数
- 修改 /auto/cc/conf 文件,将ngx_compile_opt="-c" 修改为 ngx_compile_opt="-c -g";
- 关掉Nginx的后台进程运行方式,在/conf/nginx.conf 中添加一行:
daemon off;
为什么要加-g参数?
-g 在编译的时候,产生调试信息
为什么要关闭后台进程?
nginx在启动后,在unix系统中会以daemon的方式在后台运行,后台进程包含一个master进程和多个worker进程。
我们也可以手动地关掉后台模式,让nginx在前台运行,并且通过配置让nginx取消master进程,从而可以使nginx以单进程方式运行。
很显然,生产环境下我们肯定不会这么做,所以关闭后台模式,一般是用来调试用的。
参考:Nginx开发从入门到精通
调试Master进程
- 添加VSCODE调试配置,创建并修改launch.json:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "dubug nginx",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/nginx", //nginx运行目录
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb"
}
]
}
-
调试效果
nginx_debug.jpg
调试Worker进程
- 查找Worker进程pid
Last login: Thu Jun 13 11:22:42 on ttys005
xxx:~ xx$ ps -ef | grep nginx
502 66524 1 0 9:58上午 ?? 0:00.00 nginx: master process ./bin/nginx
502 66524 0 9:58上午 ?? 0:00.00 nginx: worker process
502 68007 68009 0 11:22上午 ?? 0:00.01 /Users/ali/Documents/work/nginx-1.17.0/bin/nginx
502 68362 68132 0 11:29上午 ttys000 0:00.00 grep nginx
- 编辑 launch.json,添加 Attach配置
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "debug nginx worker",
"type": "cppdbg",
"request": "attach",
"program": "${workspaceFolder}/bin/nginx",
"processId": "69325",
"MIMode": "lldb"
},
{
"name": "debug nginx master",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/nginx",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb"
}
]
}
-
调试效果
nginx_debug_workder.jpg
总结:
1、VS Code调试真是方便,开发C/C++神器;
2、Nginx非常成熟,整个社区也是非常成熟,提供了很多资料解决很多的问题;
3、阅读Nginx代码就是一种生活享受,大家也一起来尽情遨游吧!

