Build Rails development environment in Ubuntu via Docker

Environments:
Ubuntu: 16.04.4 LTS
Docker: 18.03.1-ce, build 9ee9f40

Install Docker / Docker-compose

Assuming you have not installed Docker / Docker-compose, if you have, go to next section.

1
2
3
4
5
6
cd ~
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-get update
apt-cache policy docker-ce
sudo apt-get install -y docker-ce
sudo systemctl status docker

To run docker as without sudo:

1
sudo usermod -aG docker ${USER}

Then logout and login again.

Create folder and files

1
2
3
cd ~
mkdir docker_rails
cd docker_rails

Create the following files:

Dockerfile

1
2
3
4
5
6
7
8
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /railsapp
WORKDIR /railsapp
COPY Gemfile /railsapp/Gemfile
COPY Gemfile.lock /railsapp/Gemfile.lock
RUN bundle install
COPY . /railsapp

Gemfile

1
2
3
4
5
6
source 'https://rubygems.org'
ruby '2.5.0'
gem 'rails', '~> 5.2.0'
gem 'sqlite3'

Gemfile.lock
Create an empty file: Gemfile.lock:

1
touch Gemfile.lock

docker-compose.yml

1
2
3
4
5
6
7
8
9
version: '3'
services:
web:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/railsapp
ports:
- "3000:3000"

NT: if your docker-compose doesn’t support version 3, run the following command to upgrade docker-compose:

1
pip3 install docker-compose --upgrade

Build the project

1
docker-compose run web rails new . --force

After the above command, you will the the Rails folders/files are created as those files will be shared between host and the docker container. You will see Gemfile and Gemfile.lock have been updated.

Change permissions:

1
sudo chown -R $USER:$USER .

Now, you need to rebuild the container:

1
docker-compose build

To run the application:

1
docker-compose up

You will see the output like this:

1
2
3
4
5
6
7
8
9
10
11
Creating docker_rails_web_1 ... done
Attaching to docker_rails_web_1
web_1 | => Booting Puma
web_1 | => Rails 5.2.0 application starting in development
web_1 | => Run `rails server -h` for more startup options
web_1 | Puma starting in single mode...
web_1 | * Version 3.11.4 (ruby 2.5.1-p57), codename: Love Song
web_1 | * Min threads: 5, max threads: 5
web_1 | * Environment: development
web_1 | * Listening on tcp://0.0.0.0:3000
web_1 | Use Ctrl-C to stop

Tips

Connect to container via SSH

1
docker-compose run web bash

list files within container

1
docker-compose run web ls /etc
Share