Shiva Bhusal
Shiva's Blog

Follow

Shiva's Blog

Follow

Dockerization of Rails 6 app

Shiva Bhusal's photo
Shiva Bhusal
·Jan 15, 2019·

2 min read

Play this article

Things you need to Learn

Please visit my blog post to learn about Docker and its installation from Containarization and Docker.

Using docker-compose to dockerize the app

Steps:-

  1. Chdir to the project directory

  2. Create an entry point file called docker-entrypoint.sh

     #!/bin/bash
    
     set -e
    
     bundle check || bundle install --binstubs="$BUNDLE_BIN"
    
     echo "command executing $@"
     exec "$@"
    
  3. Create a Dockerfile with the content like below:

     FROM ruby:2.6.3
     # Needed to compile nodejs
     RUN apt-get update -qq && apt-get install -y build-essential
     RUN apt-get install -y libpq-dev
     RUN apt-get install -y libxml2-dev libxslt1-dev
     RUN apt-get install -y nodejs
    
     RUN mkdir /app
     WORKDIR /app
     ADD . /app
    
     EXPOSE 3000
    
     COPY ./docker-entrypoint.sh /
     RUN chmod +x /docker-entrypoint.sh
     ENTRYPOINT ["/docker-entrypoint.sh"]
    
     ENV BUNDLE_PATH=/bundle \
         BUNDLE_BIN=/bundle/bin \
         GEM_HOME=/bundle
     ENV PATH="${BUNDLE_BIN}:${PATH}"
     RUN gem install bundler
    
  4. Create docker-compose-yml file

     version: '3'
    
     services:
       postgres:
         image: postgres:9.6
         ports:
           - '5432:5432'
         volumes:
           - postgres:/var/lib/postgresql/data
    
       web:
         build: .
         command: puma # we are using puma
         volumes:
           - bundle:/bundle
           - .:/app
         ports:
           - '3000:3000'
         links:
           - postgres
    
     volumes:
       bundle:
       postgres:
    
  5. database.yml file need to change

    
     development:
       <<: *default
       host: postgres # service name in docker-compose.yml
       username: postgres # has to be this way
       password:
       database: my_app_development
    

    postgres is the name of the service which will be your host.

  1. Everytime you change Dockerfile, you need to rebuild the image using docker-compose build

  2. You need to create the database the first time

     docker-compose run web rails db:create && rails db:migrate && rails db:seed
    

    or you can run

    docker-compose run web rails db:create
    docker-compose run web rails db:migrate
    docker-compose run web rails db:seed

Then, your application will be available via localhost:3000 in browsers.

Summary

In this way you can move your existing Rails 5/6 projects to Docker using Docker Compose.

References

bundler.io/v2.0/guides/bundler_docker_guide..

 
Share this