23tux
23tux

Reputation: 14726

Run ruby script in docker with installed gems

What would be a quick way to run a ruby script that needs a few gems within a docker container?

I often come across the situation where I want to try out a new gem, or write a short script, and I don't want to install the gem locally. My first idea was to write a Dockerfile and build the image, e.g.

FROM ruby:latest

RUN gem install httparty
COPY test.rb /usr/app/

CMD ["ruby", "/usr/app/test.rb"]

and test.rb

require "httparty"
puts HTTParty.get("https://now.httpbin.org/").body

Then run docker build -t run-ruby-with-gems . and after the build docker run -it --rm run-ruby-with-gems

This works, but isn't handy. So maybe there is some smart one liner or anything else that could make the whole process of quickly running a ruby script easier.

Upvotes: 4

Views: 5537

Answers (1)

Jakub Bujny
Jakub Bujny

Reputation: 4628

I would strongly suggest to use docker-compose for that task. See this docker-compose.yml file:

version: '3'
services:
  ruby:
    image: ruby:latest
    command: bash -c 'gem install httparty && ruby test.rb'
    working_dir: /usr/app/
    volumes:
      - ./:/usr/app/

Place docker-compose.yml file in same directory with test.rb and then run command: docker-compose up everytime when you want to test your changes - in gems and in code.

This docker-compose configuration run command with installing gems and running your application with every up. You don't need to rebuild anything because using volume mapping you have 'hot replace' of your code directly into container.

Upvotes: 8

Related Questions