[RUBY] [Rails] How to build an environment with Docker

Development environment

・ Docker: 19.03.8 -Docker-Compose: 1.25.5 ・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina

Implementation

1. Create / move working directory

The folder name will be myapp (anything is fine).

Terminal


$ mkdir myapp

Terminal


$ cd myapp

2. Create / edit Dockerfile

Terminal


$ vi Dockerfile

Dockerfile


FROM ruby:2.7.1
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

#Added a script that runs every time the container starts
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

#Start main process
CMD ["rails", "server", "-b", "0.0.0.0"]

[Explanation]

★ Overview

FROM: Set the image and version to use RUN: Command execution WORKDIR: Set the working directory COPY: Copy local files to container ʻENTRYPOINT: Set the command to be executed first ʻEXPOSE: Set the port number on which the container listens CMD: Software execution inside the image

★ Details

** ◎ Obtain the latest stable version as of July 19, 2020 as an image to use. ** **

FROM ruby:2.7.1

** ◎ Install Node.js and PostgreSQL packages. ** **

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client

** ◎ Create a myapp directory inside the container. ** **

RUN mkdir /myapp

** ◎ Set the working directory to the myapp created above **

WORKDIR /myapp

** ◎ Copy the local Gemfile to myapp in the container. ** **

COPY Gemfile /myapp/Gemfile

** ◎ Copy the local Gemfile.lock to myapp in the container. ** **

COPY Gemfile.lock /myapp/Gemfile.lock

** ◎ Execute bundle install. ** **

RUN bundle install

** ◎ Copy the current directory (local myapp) to myapp in the container. ** **

COPY . /myapp

** ◎ Copy the local ʻentrypoint.sh to ʻusr / bin in the container. ** **

COPY entrypoint.sh /usr/bin/

** ◎ Allow access to ʻentrypoint.sh` copied above. ** **

RUN chmod +x /usr/bin/entrypoint.sh

** ◎ Set ʻentrypoint.sh` as the first command to be executed when the container is started. ** **

ENTRYPOINT ["entrypoint.sh"]

** ◎ Set the port number to 3000. ** **

EXPOSE 3000

** ◎ Launch the Rails server. ** **

CMD ["rails", "server", "-b", "0.0.0.0"]

3. Create / edit Gemfile

Specify the Rails version. This time we will make it compatible with Rails 6.

Terminal


$ vim Gemfile

Gemfile


source 'https://rubygems.org'
gem 'rails', '~> 6'

4. Create Gemfile.lock

Terminal


$ touch Gemfile.lock

5. Create / edit ʻentrypoint.sh`

Terminal


$ vi entrypoint.sh

entrypoint.sh


#!/bin/bash
set -e

#Rails compatible file server.Delete the pid as it may exist.
rm -f /myapp/tmp/pids/server.pid

#Run the container process. (The one set in CMD in the Dockerfile.)
exec "$@"

5. Create / edit docker-compose.yml

Terminal


$ vi docker-compose.yml

docker-compose.yml


version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

[Explanation]

version: Set the version of docker-compose. services: Create services in the hash below. You can name it freely, but usually you name it web and db. ʻImage: image to use (specify PostgreSQL in db) volumes: Directory mount settings (db data etc. can be left) build: Path with Dockerfile etc. (basically current directory) command: Command (delete the server.pid file and then start the rails server) ports: Port number (host: set in container) depends_on`: Shows the dependencies and allows you to specify the startup order. Here, start from db → web.

6. Check the directory structure

Terminal


myapp
- Dockerfile
- Gemfile
- Gemfile.lock
- entrypoint.sh
- docker-compose.yml

7. Build the project

Terminal


$ docker-compose run web rails new . --force --no-deps --database=postgresql --skip-bundle

[Explanation]

--force: Overwrite Gemfile --no-deps: Do not start the linked service --database = postgresql: Specify PostgreSQL for DB --skip-bundle: Skip bundle

8. Run bundle install

Terminal


Could not find gem 'pg (>= 0.18, < 2.0)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

I think that the above error occurred in 7, so execute the following command to solve it. It will bundle install when you build the Docker image.

Terminal


$ docker-compose build

9. Edit database.yml

config/database.yml


#Change before
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

#After change
default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password: password
  pool: 5

10. Start the container

Terminal


$ docker-compose up

* If the following error occurs

Terminal


Error: No such file or directory @ rb_sysopen - /myapp/config/webpacker.yml (RuntimeError)

Create / edit webpacker.yml

Terminal


touch config/webpacker.yml

webpacker.yml


# Note: You must restart bin/webpack-dev-server for changes to take effect

default: &default
  source_path: app/javascript
  source_entry_path: packs
  public_root_path: public
  public_output_path: packs
  cache_path: tmp/cache/webpacker
  webpack_compile_output: true

  # Additional paths webpack should lookup modules
  # ['app/assets', 'engine/foo/app/assets']
  additional_paths: []

  # Reload manifest.json on all requests so we reload latest compiled packs
  cache_manifest: false

  # Extract and emit a css file
  extract_css: true

  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2

  extensions:
    - .mjs
    - .js
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .jpeg
    - .jpg

development:
  <<: *default
  compile: true

  # Set to false if using HMR for CSS
  extract_css: true

  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    host: localhost
    port: 3035
    public: localhost:3035
    hmr: false
    # Inline should be set to true if using HMR
    inline: true
    overlay: true
    compress: true
    disable_host_check: true
    use_local_ip: false
    quiet: false
    pretty: false
    headers:
      'Access-Control-Allow-Origin': '*'
    watch_options:
      ignored: '**/node_modules/**'

test:
  <<: *default
  compile: true

  # Compile test packs to a separate directory
  public_output_path: packs-test

production:
  <<: *default

  # Production depends on precompilation of packs prior to booting for performance.
  compile: false

  # Cache manifest.json for performance
  cache_manifest: true

11. Create database

Terminal


docker-compose run web rake db:create

* If the following error occurs

Terminal


could not translate host name "db" to address: Name or service not known

Terminal


Error: Database is uninitialized and superuser password is not specified.

Edit docker-compose.yml

docker-compose.yml


#Change before
environment:
  POSTGRES_PASSWORD: password

#After change
environment:
  - POSTGRES_HOST_AUTH_METHOD=trust

Recommended Posts

[Rails] How to build an environment with Docker
How to build Rails 6 environment with Docker
How to build Rails, Postgres, ElasticSearch development environment with Docker
Build environment with vue.js + rails + docker
Build Rails environment with Docker Compose
How to build docker environment with Gradle for intelliJ
[Rails] How to use rails console with docker
How to build [TypeScript + Vue + Express + MySQL] environment with Docker ~ Express ~
How to build an environment with Docker, which is the minimum required to start a Rails application
[Rails] [Docker] Copy and paste is OK! How to build a Rails development environment with Docker
How to build [TypeScript + Vue + Express + MySQL] environment with Docker ~ MySQL edition ~
How to install Pry after building Rails development environment with Docker
How to build [TypeScript + Vue + Express + MySQL] environment with Docker ~ Sequelize ~
How to build API with GraphQL and Rails
[First team development ②] Build an environment with Docker
Build docker environment with WSL
How to push an app developed with Rails to Github
Build an environment of Ruby2.7.x + Rails6.0.x + MySQL8.0.x with Docker
How to make an almost static page with rails
How to build Java development environment with VS Code
[Docker + Rails] How to deal with Rails server startup failure
I tried to build an environment using Docker (beginner)
Rails + MySQL environment construction with Docker
Build Couchbase local environment with Docker
Build PlantUML environment with VSCode + Docker
[Error resolution] Occurs when trying to build an environment for spring with docker
How to get along with Rails
Build docker + laravel environment with laradock
How to build CloudStack using Docker
How to start Camunda with Docker
How to set environment variables when using Payjp with Rails
What happened in "Java 8 to Java 11" and how to build an environment
Build a Node-RED environment with Docker to move and understand
How to quit Docker for Mac and build a Docker development environment with Ubuntu + Vagrant
How to crop an image with libGDX
Rails environment construction with Docker (personal apocalypse)
Build a PureScript development environment with Docker
Create Rails 6 + MySQL environment with Docker compose
[Docker] Building an environment to use Hugo
Migrate existing Rails 6 apps to Docker environment
Deploy to heroku with Docker (Rails 6, MySQL)
Build a Wordpress development environment with Docker
Build an Ultra96v2 development environment on Docker 1
Build TensorFlow operation check environment with Docker
How to run Blazor (C #) with Docker
I tried to build the environment of PlantUML Server with Docker
Super beginner builds Rails6 + Postgresql environment with Docker to the end
I tried to build an http2 development environment with Eclipse + Tomcat
Steps to build a Ruby on Rails development environment with Vagrant
Build debug environment on container --Build local development environment for Rails tutorial with Docker-
Build a development environment for Docker + Rails6 + Postgresql
Downgrade an existing app created with rails 5.2.4 to 5.1.6
How to write Rails
How to link Rails6 Vue (from environment construction)
Rails Docker environment construction
Build an environment of "API development + API verification using Swagger UI" with Docker
Build a Laravel / Docker environment with VSCode devcontainer
How to make an application with ruby on rails (assuming that the environment has been built)
Build a WordPress development environment quickly with Docker
Rails deploy with Docker
Rails6 [API mode] + MySQL5.7 environment construction with Docker