Creating a Rails environment with Docker. This is purely a memo for myself.
Docker Community Edition for Mac
Install the stable version.
That’s all.
Check if Docker Compose is installed. It comes by default with Docker Community Edition for Mac.
$ docker-compose -v
docker-compose version 1.22.0, build f46880f
Docker Compose is commonly used in development environments and automated testing. It handles various tasks together.
$ mkdir rails
$ cd rails
Building an image for the Rails execution environment.
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp
source 'https://rubygems.org'
gem 'rails', '5.2.0'
Using postgresql
as the database.
Port is 3000.
Use volumes for data persistence. Without this, data will be lost every time the server is restarted.
version: '3'
services:
db:
image: postgres
web:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/myapp
ports:
- "3000:3000"
depends_on:
- db
At this point, your setup should look something like this:
Use docker-compose to create a Rails project.
For creating in the current directory, use rails new .
--force
will overwrite existing files.
rails$ docker-compose run web rails new . --force --database=postgresql
Once rails new is complete, you’ll see the familiar structure.
A warning appears if postgresql is 0.18, so modify it:
Gemfile
gem 'pg', '>= 0.20', '< 2.0'
After updating gems, use docker-compose build
instead of bundle install
rails$ docker-compose build
Update config/database.yml
as follows:
<!-- config/database.yml -->
default: &default
adapter: postgresql
encoding: unicode
host: db
username: postgres
password:
Start in detached mode
rails$ docker-compose up -d
Create the database
rails$ docker-compose run web rails db:create
And it’s complete.
If you want to stop currently running containers:
rails$ docker-compose stop