Create rails app using docker in 5 steps
If you want to create a new Rails application using docker, and keep it simple, these lines will help you.
Why docker ? Why no rvm or rbenv ? In the past I used to work with rvm, helping me to manage multiple ruby / rails projects. I move to docker recently not to deploy an app to this beautiful cloud (choose one you want), but to create a developer environment. This is not the first purpose of docker, but it help a lot.
I don’t need to install all of my ruby versions on my computer, not all postgresql / mysql / mariadb versions of all projects I work on, not all dependencies etc. that can conflicts between them. I can choose which unix to use (it depend on images) and get closer to production env. Docker is faster on Linux, i’m on Mac, it’s a little bit slower but it’s fine.
So let’s create a new rails app using docker, and keep it really simple. We will take an example for a standard rails 6 app using a postgresql database.
Prerequisites
- Docker
- Docker-compose
- Internet connection (download docker’s images take time ..)
5 steps
- Clone this project (it contains 3 files) : https://github.com/Pobb/docker-rails
- docker-compose build
- docker-compose run web rails new . –force –no-deps –database=postgresql –no-documentation
- Edit config/database.yml and add :
- host: db
- username: “postgres”
- password: “postgres”
- docker-compose up
Visit http://localhost:4000
and you are done !
Some explanations
docker-compose build will create docker image on your computer using our Dockerfile
. As you can see our Dockerfile is really simple. First we use official ruby image from docker hub . Next we just install some dev tools. Biggest part concern yarn : we use Rails 6
in our example, needing webpack etc. We have to setup Yarn. Next we install rails using gem install
command.
Create our rails app : in our docker-compose file we can see that we declare a web
service. We will use image we just builded and launch our classical rails new command. We mention rails new . to create app in our current folder.
Edit config/database : In our docker-compose file we can see that our db
service use postgres’s image. Here we want something really simple. By default, username and password are set to “postgres”. So mention it in your database.yml
file. Host is db : just mention it like it without quotes. It’s our db
service name we choose in docker-compose file.
Some tips
- We use volontary latest ruby version in our example (first line of Dockerfile), but I suggest you to fix your ruby version using appropriate docker image. You will find it on docker-hub website.
- As for ruby, I suggest you to precise rails version when you “gem install rails”
- You can create a docker folder and move our 3 files in (careful to change path in Dockerfile and docker-compose.yml)
- I suggest you to use ENV variable to put your user and password into database.yml file.
Sources Github project