Sunday 15 January 2017

Dockerize Rails API

How to use Docker in Rails REST API

Rails API With Docker

In the last series of tutorial we have seen "How to make REST API in 'Ruby on Rails'". Here, we will dockerize the same Rails API.

Video Tutorial:


Read Introduction to Docker if you want to learn basics of Docker.

Let's start Dockerizing our Rails API. We have already created the CRUD part of the API, now we will simply start dockerizing it by creating Dockerfile and docker-compose.yml file.

In the root directory of rails app, create Dockerfile and docker-compose.yml:

Dockerfile

FROM ruby:2.3.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /railsapi
WORKDIR /railsapi
ADD Gemfile /railsapi/Gemfile
ADD Gemfile.lock /railsapi/Gemfile.lock
RUN bundle install
ADD . /railsapi

docker-compose.yml

version: '2'
services:
  db:
    image: postgres
  webapp:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/railsapi
    ports:
      - "3000:3000"
    depends_on:
      - db

If you are wondering, what does these settings in Dockerfile/docker-compose.yml means, then it is recommended to first read Introduction to Docker.

Now, since we have these two file in place, let's build the image now by running command from the root directory of our project:

docker-compose build

This will build the image, now we can run it by running the command:

docker-compose up

Now we can access the api at http://localhost:3000/ in the browser.

If you get the following error:

Role "root" doesn't exist or Database not found, then change the following configuration in config/database.yml file

username: postgres
host: db

Also run we need to create the database.

docker-compose run webapp rake db:create

Now we can access the Rails app by creating a record using postman or curl request and get the json output on hitting the API.

0 comments:

Post a Comment

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel