Docker + Rails 6 Application setup
This tutorial will help Dockerify Rails 6 application using Postgres as database. We will see how to write Dockerfile and docker-compose file in order to create a docker image of Rails application and run it for development.
This tutorial assumes that you have basic understanding of what Docker is. Go ahead and get started with Docker to know more about Docker.
Setup Rails 6 Application
We will use Ruby 2.6.2 stable release for creating a Rails 6.0.0.beta3 application.
To install Ruby 2.6.2
using
RVM,
To install Rails 6.0.0.beta3,
Create a Ruby on Rails application with,
This will setup a new Rails 6.0.0.beta3 application. Once that is done, change directory to newly created directory.
Create a Dockerfile
Create a Dockerfile to build a Docker image of the Rails application.
For the configuration discussed above, we can use Dockerfile
listed below.
Listing down details of the Dockerfile.
- It will use ruby image of version 2.6.2
- Install node and npm to be able to install node based dependencies of the project
- Install bundler and foreman
- Copy
Gemfile
andGemfile.lock
andbundle install
the project - Install yarn globally and
yarn install
dependencies - Expose port
3000
to be able to access rails application from outside
Create .dockerignore file
Create a .dockerignore
file.
This is same as .gitignore
file
but
used to list files which need to be ignored
when docker image is build for the project.
Create Docker Compose
Docker compose is a tool to build multi container application. As, we will be using Ruby on Rails application with postgres, we will use two services in docker compose as listed below.
db
- db is a service that use
postgres
as image from docker hub. - It runs on the port
5432
.
web
- This build
.
current directory for the container. - This use
/app
volume for the container - Expose port 3000 from container
- Depends on
db
container.db
container starts beforeweb
container. environment
option can be used to define environment variables
Typical database.yml
file can be as given below,
that uses correct database url in the docker image.
Rails DB Setup
We can run rake
/ rails tasks in docker container for Rails application
with command given below.
This will setup create database and seed data.
Start Rails application with Docker
Now, we can run the project in development mode with the command given below.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox