We introduced Docker so that team members who have not built a Rails environment can easily run the project locally without the hassle of building the environment. Since I am building the Rails environment locally, I created the project locally so that both Docker and local direct can work. It is assumed that Docker is already installed.
$ mkdir myapp; cd $_
$ rails new . --skip-coffee --skip-turbolinks --database=postgresql
Depending on the environment variable, you can choose to run it with Docker or directly locally.
Gemfile
gem 'dotenv-rails'
install gem
$ bundle install
The following is an example of setting environment variables when running with Docker.
.env
DATABASE_HOST=db
DATABASE_USER=postgres
DATABASE_PASSWORD=secret
Set DATABASE_HOST = localhost
to run directly locally.
docker-compose.yml
version: '3'
services:
db:
image: postgres
volumes:
- ./tmp/db:/var/lib/postgresql/data
ports:
- "5433:5432"
environment:
POSTGRES_USER: 'postgres'
POSTGRES_PASSWORD: 'secret'
POSTGRES_DB: 'db'
webpacker:
build: .
command: bundle exec bin/webpack-dev-server
volumes:
- .:/myapp
ports:
- "8080:8080"
web:
build: .
command: /bin/sh -c "rm -f /myapp/tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
- .:/myapp
ports:
- "3000:3000"
depends_on:
- db
- webpacker
dockerfile
FROM ruby:2.7.1
ENV LANG C.UTF-8
#Install the required libraries
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
#yarn package management tool installation
RUN apt-get update && apt-get install -y curl apt-transport-https wget && \
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && apt-get install -y yarn
#Work directory settings
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp
EXPOSE 3000
Added host
, ʻusername, and
passwrdsettings to
database.yml`
/config/database.yml
:abridgement
default: &default
adapter: postgresql
encoding: unicode
host: <%= ENV.fetch("DATABASE_HOST") { "127.0.0.1" } %> #Postscript
username: <%= ENV.fetch("DATABASE_USER") { "postgres" } %> #Postscript
password: <%= ENV.fetch("DATABASE_PASSWORD") { "" } %> #Postscript
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
:abridgement
$ docker-compose build
$ docker-compose run --rm web bin/yarn install
$ docker-compose run --rm web rails db:create
$ docker-compose up
You can access http: // localhost: 3000 /.
Edit .env
and launch it with yarn install
, rails db: create
, rails s
.
Recommended Posts