TIL: Dockerize rails new app
Every time that I have to start a new project (Ruby, Rails, JS…) I always start Docker first! This means, I never install a single Gem or Package on my local machine.
It helps me to avoid conflicts with different versions of the same package, lost dependencies in the system and so on.
Everything that I use for development on my laptop runs in a Docker container, even Neovim.
This is an example of how to create, step by step, a Ruby on Rails API + Postgres and the only thing you need to follow is Docker.
So let’s start:
# Create the directory for the API
1$ mkdir docker-compose-rails-api
2$ cd docker-compose-rails-api
# Create the Dockerfile
1FROM ruby:2.7.3
2LABEL Description="Docker Rails API Base"
3WORKDIR /app
4
5RUN gem install bundler
6
7CMD exec bin/start.sh
# Create the Gemfile
1source "https://rubygems.org"
2
3ruby "2.7.3"
4gem "rails", "~> 6.1.3.2"
# Create the docker-compose.yml
1version: "3"
2services:
3 api:
4 restart: on-failure
5 build: .
6 tty: true
7 stdin_open: true
8 volumes:
9 - .:/app
10 - bundle_cache:/usr/local/bundle
11 ports:
12 - "3000:3000"
13 depends_on:
14 - db
15 environment:
16 DATABASE_URL: postgresql://postgres@db/api_development
17 TEST_DATABASE_URL: postgresql://postgres@db/api_test
18 db:
19 image: postgres:latest
20 volumes:
21 - ./docker/data-volume/postgresql:/var/lib/postgresql/data
22 ports:
23 - 5456:5432
24 environment:
25 POSTGRES_HOST_AUTH_METHOD: trust
26volumes:
27 bundle_cache:
# Create a bin/start.sh file
1bundle check || bundle install
2
3if [ -f tmp/pids/server.pid ]; then
4 rm -f tmp/pids/server.pid
5fi
6
7bin/rails s -p 3000 -b 0.0.0.0
# And set permissions
1$ chmod +x bin/start.sh
# Install Rails
1$ docker-compose run api gem install rails -v 6.1.3.2
# Create the Rails API
1$ docker-compose run api rails new . --api --force --database=postgresql --skip-bundle
# Replace content of config/database.yml with this:
1global: &default
2 adapter: postgresql
3 pool: 5
4 url: <%= ENV["DATABASE_URL"] %>
5
6 development:
7 <<: *default
8
9 test:
10 <<: *default
11 url: <%= ENV["TEST_DATABASE_URL"] %>
12
13 production:
14 <<: *default
# Start the server
1$ docker-compose up -d
# Create the database
1$ docker-compose run api bin/rails db:create