For a considerable period, we relied on rails console
for debugging within our app running inside a Docker container. The challenge lay in the necessity to consistently enter the container and execute bundle exec rails console
to ensure a context-aware console, this approach didn't offer the optimal Developer Experience. While exploring alternative options, I discovered the debug
gem, which can be extended with Visual Studio Code (VSCode) extensions such as RDBG."
Setup
Let's get everything set up for a seamless debugging experience. Follow these steps:
- Install the debug gem locally:
gem install debug
- Add the gem to your Gemfile under the development group:(and do a
bundle install
inside the respective app contianer):
group :development do
gem 'debug'
end
- install
KoichiSasada.vscode-rdbg
vscode extension
Now it is time to integrate all of these together, the approcah would be to run the debugger programmatically and run the debugger inside an initializer file, create a Ruby file under config/initializers (e.g., config/initializers/debug.rb) with the following content::
# e.g. config/initializers/debug.rb
if Rails.env.development?
require 'debug/session'
Rails.logger.info "Starting debug session"
# the port can be anything
DEBUGGER__.open(port: "12345", host: "0.0.0.0")
end
Don't forget to add the port to your Docker Compose file and map it to your desired host machine port:
version: "2.3"
services:
<your_service_name>:
ports:
- "12345:12345"
this will make the remote debugging possible and connecting to the ruby porcces running inside the container directly from vscode.
Now we have to take care of launch.json
file for vscode with proepr config. at root of your project create a .vscode/launch.json
and paste the following:
{
"configuration": [
{
"type": "rdbg",
"name": "Attach with rdbg local",
"request": "attach",
"debugPort": "12345" <--- this is tha mapped port from compose file
}
]
}
this will create a profile in the Run and debug
pannel of vscode which can attach to running ruby proccess inside the docker container
Now we have everything set. run your rails server and you will see something like:
Starting debug session
DEBUGGER: Debugger can attach via TCP/IP (0.0.0.0:12345)
Now you're all set! Connect to the debugger and use binding.b
anywhere in your code for a full debugging experience.
Phusion passenger users
If you're running your app through Passenger, ensure the following configurations to prevent Passenger from killing your idle Ruby processes:
passenger_max_preloader_idle_time 0;
passenger_pool_idle_time 0;
read more about these configs here
Note: These configs are generally recommended for local development only.
Happy debugging! ๐
Top comments (2)
Dummy question.. Can I use this to debug staging env?
do you mean something like remote debugging and attaching to a container on server in staging environment?