Starting a new Rails project using Docker
If you’ve been considering using and learning Docker for a while, I highly suggest to just do it. It is a great way to adhere to the 12 Factor App methodology. Docker is a method of containerization, this gives developers an easy way to develop in the exact same environment that your production system will be running. If you are just starting off with Docker, it can be a daunting experience, especially if you are use to building conventional Rails applications. Hopefully this blog post can get you started.
Before you can start any rails development, you’ll need a rails app. With Docker, you will first need to “bootstrap” your environment to gain access to the rails executable to initialize a new application. The following Dockerfile defines a new image to be built from
ruby:2.4.1 which is derived from a basic Debian image. In our example,
/app will be used as the directory where the app will live in the container.
FROM ruby:2.4.1 RUN mkdir /app WORKDIR /app
Next we can create a Gemfile and add the rails gem. Feel free to set a specific version if needed.
source 'https://rubygems.org' gem "rails"
Build and bash #
Now we can build the “bootstrapped” image and start a bash prompt. The
-v switch is important as it will mount a local directory to a volume on the container. This mount is needed to get generated files from the container, back to your local filesystem.
$ docker build -t tag . $ docker run -v /home/roel/src/example:/app -it tag bash
Bundle install from container #
Once the bash prompt is started in the container, install the gems and create the rails project as needed.
$ bundle install $ rails new .
New Dockerfile #
Now we need to slightly modify our Dockerfile so that our new image will be usable and deployable. The idea here is to copy the Gemfile files in isolation and then run
bundle install. This will be the ideal method going forward when installing gems. For more details about this, checkout my previous post about updating the Gemfile under Docker
FROM ruby:2.4.1 RUN apt-get update && apt-get install -y nodejs RUN mkdir /app WORKDIR /app ADD Gemfile /app/Gemfile ADD Gemfile.lock /app/Gemfile.lock RUN bundle install ADD . /app
Now rebuild the image using the newly updated Dockerfile. You may need to sit tight while the image builds from scratch, installs nodejs, and installs all the gems.
$ docker build -t tag .
Start the rails server by issuing another
docker run command. The
-p option will allow you to bind a port on your host machine to a running container. This will allow you to access the rails web server from your localhost.
$ docker run -p 3000:3000 tag rails server -b 0.0.0.0 -p 3000
Hope you found this post useful, as always, feel free to reach out to me with any questions or concerns.