Beginners Guide to Docker with Rails

In this article I show you how to get a Rails application working with Docker.

Install Docker Toolbox

Begin by installing the Docker Toolbox on Mac OSX. Download it and follow the installer steps.

Once it is done, open:

Applications/Docker/Docker Quickstart Terminal

Docker Toolbox comes with everything you need - Docker Client, Docker Machine, Docker Compose, Docker Kitematic, and VirtualBox.

That will take a little time. If it completes successfully, you will see the Docker Whale. In terminal, can now type docker to see all available commands.

Note: if you see instructions for Boot2Docker installations, ignore those. It is an old method of installing Docker.

Create the Dockerfile

Begin by creating a Dockerfile in the root directory of your Rails project (where your README file lives).

Note: A Dockerfile is a lot like a Gemfile but instead of specifying ruby version and ruby libraries, it specifies the operating system and system libraries your Rails app will run on.

touch Dockerfile

Paste the following into that Dockerfile.

FROM phusion/passenger-ruby21:0.9.18

# Set correct environment variables
ENV HOME /root

# Use baseimage-docker's init process
CMD ["/sbin/my_init"]

# Start Nginx / Passenger
RUN rm -f /etc/service/nginx/down

# Remove the default site
RUN rm /etc/nginx/sites-enabled/default

# Add the nginx info
ADD nginx.conf /etc/nginx/sites-enabled/webapp.conf

# Prepare folders
RUN mkdir /home/app/webapp

# Run Bundle in a cache efficient way
ADD Gemfile /tmp/
ADD Gemfile.lock /tmp/
RUN bundle install

# Add the rails app
ADD . /home/app/webapp

# Run migrations
WORKDIR /home/app/webapp
RUN bundle exec rake db:create db:migrate

# Clean up APT when done
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

The Dockerfile above is using Passenger with NGINX to serve the Rails app on.

Create the nginx.conf file

Create the nginx.conf file.

server {
  listen 80;
  root /home/app/webapp/public;

  passenger_enabled on;
  passenger_user app;

  passenger_ruby /usr/bin/ruby2.1;

Build and run the Docker image

Now, you are ready to build the image.

docker build --tag webapp .

Next, run the image (as a container).

docker run -p 80:80 -d -v $(pwd):/home/app/webapp webapp

Running the image is a lot like running bin/rails s

Lastly, visit your running Rails application by checking the IP address of docker-machine.

docker-machine ip

Visit the IP address that docker-machine ip displays. You will see your application running. That's it!