You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用VSCode调试Docker容器中基于Puma运行的Rails应用?

调试Docker中Puma启动的Rails应用(rdbg方式)

问题分析

当前配置存在几个核心问题导致调试失败:

  • Puma启用了多Worker模式,preload_app!的fork机制会导致调试会话无法继承到子Worker进程
  • 启动命令未触发rdbg调试监听
  • Docker未映射调试端口到主机
  • VSCode调试配置缺少关键参数

1. 修改Puma配置适配调试

调整config/puma.rb,解决多进程调试冲突:

# 开发环境强制单Worker,避免多进程调试问题
if ENV['RACK_ENV'] == 'development'
  workers 1
else
  workers Integer(ENV['WEB_CONCURRENCY'] || 2)
end

threads_count = Integer(ENV['MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup DefaultRackup
port ENV['PORT'] || 3000
environment ENV['RACK_ENV'] || 'development'

if ENV['RACK_ENV'] == 'development'
  worker_timeout 3600 # 防止调试超时
end

before_fork do
  Barnes.start # 保留原有 metrics 初始化
  # 多Worker场景下标记调试进程fork状态
  if ENV['RACK_ENV'] == 'development' && defined?(Rdbg)
    Rdbg.mark_as_forked
  end
end

# 开发环境启动rdbg远程监听
if ENV['RACK_ENV'] == 'development'
  require 'rdbg'
  Rdbg.start_with_server(host: '0.0.0.0', port: 12345)
end

2. 配置Docker端口映射

确保容器的调试端口映射到主机:

  • 直接启动Docker时添加参数:
docker run -p 3000:3000 -p 12345:12345 your-rails-image
  • 或在docker-compose.yml中配置:
services:
  web:
    ports:
      - "3000:3000"
      - "12345:12345"
    # 其他镜像、环境变量配置...

3. 完善VSCode调试配置

更新.vscode/launch.json:

{
  "type": "rdbg",
  "name": "Attach to Docker Rails",
  "request": "attach",
  "debugPort": "localhost:12345",
  "remote": true,
  "cwd": "${workspaceFolder}",
  "localfs": "${workspaceFolder}",
  "remotePath": "/app" // 替换为容器内Rails应用的实际路径
}

4. 启动应用的正确命令

用rdbg包裹启动命令,触发调试监听:

bundle exec rdbg -O -c -- bundle exec puma -C config/puma.rb -b 'tcp://0.0.0.0:3000'

参数说明:

  • -O:启用远程调试服务器
  • -c:启动后自动继续运行(不暂停在入口)

验证步骤

  1. 启动Docker容器,确认容器内12345端口处于监听状态
  2. 在VSCode的Rails代码中设置断点(如控制器方法内)
  3. 启动调试会话(选择"Attach to Docker Rails")
  4. 访问应用接口触发断点,检查是否能命中调试器

内容的提问来源于stack exchange,提问作者Tzook Bar Noy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:35:11