Docker and rails

Some time ago I took a look at ruby on rails as a more productive environment for every day projects. For my experience with it I will publish a seperate post. So here I want to line out a possible workflow with rails and docker since everything I have seen so far, lacks some essential parts. The following actions are taken on a simple standard rails project generated with rails new app.

Running the application within a container

The base requirement is to run the whole application within a container. Using docker-compose this is fairly simple. We need a compose file which covers a web container that runs the rails server command.

When starting this thing using docker-compose up you see an error message that shows that the rails command can not be found. True, we don’t have rails within our container. It’s just a base ruby v2.2.2 image we use. As we all know, rails is a ruby gem. So here comes the tricky part. How do you manage your gem dependencies?

Managing dependencies

The tutorial on suggests to build your own image based on the ruby image and bake rails right in. This is a nice idea but it’s cumbersome during development because of some reasons:

  • bundler isn’t able to track existing dependencies. So bundle install ends up making a full installation every time since the already installed gems aren’t persisted.
  • After installing a new gem, you have to rebuild the image.

My suggestion is to generate your project using a locally installed rails and mount this directory as a volume into a container based on a ruby image as seen above. To install dependencies, install them locally using a one shot container and a special bundle app config. The app config looks like the following:

Save this file under .bundle/config. Above you can see, that we hand this file to the container using the environment variable BUNDLE_APP_CONFIG. Now we can install everything within our Gemfile using a one-shot container:

The warning, spit out by bundler about root privileges, can be safely ignored.

Now you can boot your container using docker-compose up.

Working with rails tools

There are some tools related to rails like the console (spawned with rails console) or byebug with which you can debug your application. We need some tricks to use them in a dockerized rails application. The console is the easier case. Spawn one with:

The other tool is byebug. To use it, we have to run docker-compose in daemon mode and attach to the web container:

Replace myapp_ with the name of the folder the application resides in (without all dashes, whitespaces and stuff). This will boot the composition and show a debugger console you can interact with when a byebug breakpoint comes up.