Ruby in Docker
| The ruby image | |
| Run one-liners | |
| Mount your script | |
| Install gems inside |
The ruby image
Docker lets you run Ruby without installing it on the host. The official ruby image on the hub carries ready builds for each release line.
The ruby:3 tag follows the Ruby 3 line, so it is a good default for this course. You do not need to remember digests or variants yet.
Run one-liners
The fastest check is a one-liner that prints the Ruby version from inside a fresh container. The container is removed automatically after it runs:
Print Ruby version from Docker
docker run --rm ruby:3 ruby -v
ruby 3.3.0 (2023-12-25 revision 7b0c32346b) [x86_64-linux]
The first run may download the image, so it can take a while. Later runs reuse the cached image and start instantly.
Mount your script
To run your own file, mount the current folder into the container and set it as the working folder. Then ask the container Ruby to run your script by name:
Run main.rb from the current folder
docker run --rm -v "$PWD":/app -w /app ruby:3 ruby main.rb
hello from Docker
The mount flag shares files both ways, so edits on the host are visible inside the container at once. Keep script names simple while you learn the flags.
Install gems inside
Gems installed inside a plain run command live only as long as that container lives. That behavior is handy for quick trials and keeps the host clean.
For a repeatable setup, write a small Dockerfile that starts from the ruby image and installs the gems you need. Rebuild the image when the gem list changes and run scripts from the new image.
Next: Ruby course
Article author: Arthur Isaev