如何配置Cloud Shell Editor的launch.json,实现通过VM实例调试应用
配置Cloud Shell Editor远程调试GCE VM内的应用
1. 前置准备:VM环境与防火墙配置
- 先在GCE VM中安装对应开发语言的调试工具:
- Python:
sudo apt-get update && sudo apt-get install python3-pip && pip3 install ptvsd - Node.js:
npm install -g node-inspect
- Python:
- 在GCP防火墙规则中开放调试端口(如Python默认5678、Node.js默认9229),允许Cloud Shell的IP段访问(临时测试可放宽至
0.0.0.0/0,生产环境务必限制IP范围)。
2. 建立Cloud Shell Editor与VM的SSH远程连接
- 打开Cloud Shell Editor的命令面板(
Ctrl+Shift+P),输入Remote-SSH: Connect to Host,选择Add New SSH Host。 - 输入SSH命令:
gcloud compute ssh <VM实例名称> --zone <VM所在区域>,保存到默认配置文件。 - 选中刚添加的主机完成连接,等待编辑器加载远程环境。
3. 编写launch.json调试配置
根据你的开发语言,使用以下对应配置:
Python调试配置示例
在项目根目录的.vscode/launch.json中写入:
{ "version": "0.2.0", "configurations": [ { "name": "远程Python调试", "type": "python", "request": "attach", "port": 5678, "host": "<VM公网IP>", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/VM上的代码绝对路径" } ] } ] }
- 先在VM终端启动带调试服务的代码:
python3 -m ptvsd --host 0.0.0.0 --port 5678 --wait 你的脚本名.py - 回到Cloud Shell Editor启动该调试配置,即可断点调试。
Node.js调试配置示例
{ "version": "0.2.0", "configurations": [ { "name": "远程Node.js调试", "type": "node", "request": "attach", "port": 9229, "host": "<VM公网IP>", "localRoot": "${workspaceFolder}", "remoteRoot": "/VM上的代码绝对路径", "skipFiles": ["<node_internals>/**"] } ] }
- 在VM终端启动带调试参数的应用:
node --inspect=0.0.0.0:9229 你的应用名.js - 启动Cloud Shell Editor的调试配置即可连接调试。
4. 关键注意事项
- 用
telnet <VM公网IP> <调试端口>测试Cloud Shell到VM的端口连通性,不通则检查防火墙规则。 - 路径映射必须精确匹配本地与VM的代码目录,否则断点无法触发。
- 调试完成后,务必关闭调试端口的防火墙规则,避免安全暴露。
内容的提问来源于stack exchange,提问作者Gustavo Lescowicz Kotarsky
相关产品推荐
相关产品推荐

