web_bonsaiの日記

web開発の学習日記です。誰に見せるためでもないただの日記です。

Docker Composeを使ってローカルでRails7のスタートページを表示するところまでやってみる | Mac + Docker + Rails その0005

参考にさせていただいたページ

今日の環境

参考ページについて

基本的には公式の「Quickstart: Compose and Rails | Docker Documentation」に倣ってやっていきますが、rails7に対応するために「Rails 7 + MySQLの環境構築をDocker composeで作る - Qiita」を参考にやっていこうと思います。

プロジェクトディレクトリを作成して移動

ディレクトリ名は何でも良いです。

このあと作成していく設定ファイルの記述内容にも影響しません。

mkdir rails_sample
cd rails_sample

Dockerfileの作成とその記述内容

vim Dockerfile

2022年05月13日現在で最新の安定版はruby3.1.2らしく、docker hubにも ruby:3.1.2 があることが確認できたので、それを使おうと思います。

Rails 7 + MySQLの環境構築をDocker composeで作る - Qiita」も参考にしつつ、以下のように記述しました。

FROM ruby:3.1.2

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client vim
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]

Gemfileの作成とその記述内容

vim Gemfile

参考ページに記載されているものから、バージョンを上げてrails7にしてみます。

以下の通り記述します。

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

空のGemfile.lockを作成

dockerコンテナの中にコピーして使うので空ファイルを作成しておきます。

touch Gemfile.lock

entrypoint.shの作成とその記述内容

以下の説明の通りですが、 server.pid というファイルが削除されずにrailsサーバーが起動できなくなったりするので、entrypoint.sh というファイルを作成して、server.pidを削除するコマンドを記述します。

Next, provide an entrypoint script to fix a Rails-specific issue that prevents the server from restarting when a certain server.pid file pre-exists. This script will be executed every time the container gets started. entrypoint.sh consists of:

エディタは何でも良いですが、vimで。

vim entrypoint.sh

参考ページに倣って、以下の通り記述します。

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

docker-compose.ymlの作成とその記述内容

vim docker-compose.yml
version: "3.9"
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

ここまでやった段階でのディレクトリ構造とファイル構成

最初に作成したrails_sampleディレクトリに、以下のようにファイルがあるだけです。

.
├── Dockerfile
├── Gemfile
├── Gemfile.lock
├── docker-compose.yml
└── entrypoint.sh

rails newする

参考ページに倣って、以下のコマンドを実行します。--rmだけ追加しています。

docker-compose run --rm --no-deps web rails new . --force --database=postgresql

rails newされて、railsのプロジェクトが生成されます。

このときGemfileやGemfile.lockが更新されます。

以下のようなエラーが赤字で出力されました。

Could not find gem 'sprockets-rails' in locally installed gems.
       rails  importmap:install
Could not find gem 'sprockets-rails' in locally installed gems.
Run `bundle install` to install missing gems.
       rails  turbo:install stimulus:install
Could not find gem 'sprockets-rails' in locally installed gems.
Run `bundle install` to install missing gems.

bundle installする

以下のコマンドを実行します。

docker-compose run web bundle install

白字なのでエラーではなさそうですが以下のメッセージが表示されました。

RubyZip 3.0 is coming!
**********************

The public API of some Rubyzip classes has been modernized to use named
parameters for optional arguments. Please check your usage of the
following classes:
  * `Zip::File`
  * `Zip::Entry`
  * `Zip::InputStream`
  * `Zip::OutputStream`

Please ensure that your Gemfiles and .gemspecs are suitably restrictive
to avoid an unexpected breakage when 3.0 is released (e.g. ~> 2.3.0).
See https://github.com/rubyzip/rubyzip for details. The Changelog also
lists other enhancements and bugfixes that have been implemented since
version 2.3.0.

docker-compose buildする

参考ページに倣って以下のコマンドを実行します。

docker-compose build

railsのデータベース設定をする

参考ページに倣って、config/database.ymlを以下の通りになるように編集します。

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

development:
  <<: *default
  database: myapp_development


test:
  <<: *default
  database: myapp_test

たぶんdefaultの host, username, password の項目を追記するだけだと思います。

docker-compose upする

参考ページに倣って、以下のコマンドで、webとdbのサーバーを起動します。

docker-compose up

localhost:3000にアクセスしてみる

ActiveRecord::NoDatabaseError が表示されました。

db createする

docker-compose stopはしなくても良いので、参考ページに倣って、別タブで以下のコマンドを実行してDBを作成します。

docker-compose run web rails db:create

localhost:3000にアクセスし直す

http://localhost:3000/」にアクセスしたら、railsのスタートページが表示されました。

Docker Composeを使ってローカルでRails6のスタートページを表示するところまでやってみる | Mac + Docker + Rails その0004

参考にさせていただいたページ

今日の環境

参考ページについて

基本的には公式の「Quickstart: Compose and Rails | Docker Documentation」に倣ってやっていきますが、rubyrailsのバージョンを新しめのものにして環境構築していきます。

プロジェクトディレクトリを作成して移動

ディレクトリ名は何でも良いです。

このあと作成していく設定ファイルの記述内容にも影響しません。

mkdir rails_sample
cd rails_sample

Dockerfileの作成とその記述内容

vim Dockerfile

2022年05月13日現在で最新の安定版はruby3.1.2らしく、docker hubにも ruby:3.1.2 があることが確認できたので、それを使おうと思います。

docker-compose + rails6 環境構築」のページを参考にRails6に合うように記述します。

# syntax=docker/dockerfile:1
FROM ruby:3.1.2

## nodejsとyarnはwebpackをインストールする際に必要
# yarnパッケージ管理ツールをインストール
RUN 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

RUN apt-get update -qq && apt-get install -y nodejs build-essential libpq-dev postgresql-client yarn vim
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install

RUN yarn install --check-files
RUN bundle exec rails webpacker:install

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]

Gemfileの作成とその記述内容

vim Gemfile

参考ページに記載されているものから、バージョンを上げてrails6にしてみます。

以下の通り記述します。

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

空のGemfile.lockを作成

dockerコンテナの中にコピーして使うので空ファイルを作成しておきます。

touch Gemfile.lock

entrypoint.shの作成とその記述内容

以下の説明の通りですが、 server.pid というファイルが削除されずにrailsサーバーが起動できなくなったりするので、entrypoint.sh というファイルを作成して、server.pidを削除するコマンドを記述します。

Next, provide an entrypoint script to fix a Rails-specific issue that prevents the server from restarting when a certain server.pid file pre-exists. This script will be executed every time the container gets started. entrypoint.sh consists of:

エディタは何でも良いですが、vimで。

vim entrypoint.sh

参考ページに倣って、以下の通り記述します。

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

docker-compose.ymlの作成とその記述内容

vim docker-compose.yml
version: "3.9"
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

ここまでやった段階でのディレクトリ構造とファイル構成

最初に作成したrails_sampleディレクトリに、以下のようにファイルがあるだけです。

.
├── Dockerfile
├── Gemfile
├── Gemfile.lock
├── docker-compose.yml
└── entrypoint.sh

rails newする

参考ページに倣って、以下のコマンドを実行します。--rmだけ追加しています。

docker-compose run --rm --no-deps web rails new . --force --database=postgresql

rails newされて、railsのプロジェクトが生成されます。

このときGemfileやGemfile.lockが更新されます。

正常に完了したようですが、以下のようなメッセージが表示されているのでちゃんと読んでおくと良さそうです。

hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint: 
hint:   git config --global init.defaultBranch <name>
hint: 
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint: 
hint:   git branch -m <name>
You don't have net-smtp installed in your application. Please add it to your Gemfile and run bundle install
Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/

docker-compose buildする

参考ページに倣って以下のコマンドを実行します。

docker-compose build

railsのデータベース設定をする

参考ページに倣って、config/database.ymlを以下の通りになるように編集します。

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

development:
  <<: *default
  database: myapp_development


test:
  <<: *default
  database: myapp_test

たぶんdefaultの host, username, password の項目を追記するだけだと思います。

docker-compose upする

参考ページに倣って、以下のコマンドで、webとdbのサーバーを起動します。

docker-compose up

webpacker.ymlが無いのでexited with code 1になった

exited with code 1 になってしまったので、よく読むと以下のようなメッセージが出力されていました。

webpacker.ymlが無いので rails webpacker:install を実行してくださいと書いてありました。

rails6_sample-web-1  | /usr/local/bundle/gems/webpacker-5.4.3/lib/webpacker/configuration.rb:103:in `rescue in load': Webpacker configuration file not found /myapp/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /myapp/config/webpacker.yml (RuntimeError)
rails6_sample-web-1  | Exiting
rails6_sample-web-1  | /usr/local/lib/ruby/3.1.0/psych.rb:670:in `initialize': No such file or directory @ rb_sysopen - /myapp/config/webpacker.yml (Errno::ENOENT)

webpackerをインストールする

以下のコマンドを実行しました。

docker-compose run web rails webpacker:install

localhost:3000にアクセスしてみる

ActiveRecord::NoDatabaseError が表示されました。

db createする

参考ページに倣って、以下のコマンドでDBを作成します。

docker-compose run web rails db:create

docker-compose upし直す。

docker-compose up

localhost:3000にアクセスし直す

http://localhost:3000/」にアクセスしたら、railsのスタートページが表示されました。

rails7の環境構築にも挑戦してみようかと思います。

Docker Composeを使ってローカルでRails5のスタートページを表示するところまでやってみる | Mac + Docker + Rails その0003

参考にさせていただいたページ

今日の環境

前提となる準備

端末自体には同じバージョンをインストールしなくても、Dockerのコンテナ内にはrubyがインストールされているので環境構築はできちゃうみたいだけど、一応インストールされている方が良いのだろうか...?

  • rbenvのrubyのパスが通っているか
  • Dockerfileのrubyバージョンと同じバージョンのrubyのパスが通っているか rbenv versions, ruby -v
  • rbenvのrubyにbundlerが入っているか gem list, gem install bundler
  • bundlerのパスがrbenvのrubyであるか which bundler

failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount083584404/Dockerfile: no such file or directory

手順を実行していく途中で、以下のようなエラーが表示される場合はDockerfileが無いとか、DockerFileみたいにFが大文字になっていてファイル名が間違っているとかそういうことかもしれません。

failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount083584404/Dockerfile: no such file or directory

参考ページについて

今回はとにかく公式の「Quickstart: Compose and Rails | Docker Documentation」に倣ってやっていきます。

まずは公式。

Rails5だと古いのですが、まずはそのままやってみます。

プロジェクトディレクトリを作成して移動

mkdir rails_sample
cd rails_sample

Dockerfileの作成とその記述内容

vim Dockerfile

Quickstart: Compose and Rails | Docker Documentation」に倣って以下の通り作成してみます。

# syntax=docker/dockerfile:1
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client vim
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]

Gemfileの作成とその記述内容

vim Gemfile

参考ページに倣って以下の通り記述します。

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

空のGemfile.lockを作成

dockerコンテナの中にコピーして使うので空ファイルを作成しておきます。

touch Gemfile.lock

entrypoint.shの作成とその記述内容

以下の説明の通りですが、 server.pid というファイルが削除されずにrailsサーバーが起動できなくなったりするので、entrypoint.sh というファイルを作成して、server.pidを削除するコマンドを記述します。

Next, provide an entrypoint script to fix a Rails-specific issue that prevents the server from restarting when a certain server.pid file pre-exists. This script will be executed every time the container gets started. entrypoint.sh consists of:

何でも良いですが、vimで。

vim entrypoint.sh

参考ページに倣って、以下の通り記述します。

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

docker-compose.ymlの作成とその記述内容

version: "3.9"
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

rails newする

参考ページに倣って、以下のコマンドを実行します。

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

rails newされて、railsのプロジェクトが生成されます。

このときGemfileやGemfile.lockが更新されます。

docker-compose buildする

参考ページに倣って以下のコマンドを実行します。

docker-compose build

データベースに接続する

参考ページに倣って、config/database.ymlを以下の通り編集します。

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

development:
  <<: *default
  database: myapp_development


test:
  <<: *default
  database: myapp_test

たぶんdefaultの host, username, password の項目を追記するだけだと思います。

docker-compose upする

参考ページに倣って、以下のコマンドで、webとdbのサーバーを起動します。

docker-compose up

localhost:3000にアクセスしてみる

http://localhost:3000/」にアクセスしたら、以下のようなエラーが出ました。

could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

railsの config/database.yml の変更を反映したいので、一度stopしてupしなおします。

docker-compose stopする

一度stopします。

db createする

参考ページに倣って、以下のコマンドでDBを作成します。

docker-compose run web rake db:create

docker-compose upし直す。

docker-compose up

localhost:3000にアクセスし直す

http://localhost:3000/」にアクセスしたら、railsのスタートページが表示されました。

rubyrailsのバージョンが古いので、新しいバージョンで後日もう一度挑戦しようと思います。

サーバーを止める

以下のコマンドで止められます。

docker-compose stop

サーバーを起動する

以下のコマンドで起動できます。

docker-compose start

不要なコンテナが残っていないか確認する

以下のコマンドでコンテナの一覧を表示できます。

docker ps -a

不要なコンテナを削除する

止まっているコンテナは、以下のコマンドで削除できます。

docker rm コンテナID

rbenvでrubyをインストールする | Mac + Docker + Rails その0002

参考にさせていただいたページ

今日の環境

前提

  • hogebrewをインストールしておく

brewでrbenvをインストール

rbenvとruby-buildをインストールします。

brew install rbenv ruby-build

rbenvのバージョン確認

一応バージョン確認をします。

rbenv -v

rbenvでインストールできるバージョンを確認

各バージョンの安定版だけ表示されると思います。

rbenv install --list

インストールする

とりあえず今回は 3.0.4 をインストールしてみます。

rbenv install 3.0.4

インストール済みのrubyバージョンを確認する

以下のコマンドでインストール済みのバージョンと使用中のバージョンが確認できます。

rbenv versions

ディレクトリ内で使用するバージョンを設定する

以下のコマンドで設定します。

rbenv local 3.0.4

このとき .ruby-version というファイルが生成されます。

バージョンが設定されたか確認する

以下のコマンドで 3.0.4 になっているか確認します。

rbenv versions

以下のコマンドを実行すると実際にはまだ切り替わっていないと思います。

ruby -v

パスを通す

以下のコマンドを実行します。

rbenv init

以下の通り表示されました。

# Load rbenv automatically by appending
# the following to ~/.zshrc:

eval "$(rbenv init - zsh)"

~/.zshrceval "$(rbenv init - zsh)" と記述してください。とのことなので、以下の通り追記します。

eval "$(rbenv init - zsh)"

.zshrcの設定を反映します。

source ~/.zshrc

バージョンが設定されたか再度確認する

以下のコマンドで確認します。

ruby -v

無事に ruby 3.0.4 が反映されました。

dockerのHelloWorldまでやってみる | Mac + Docker + Rails その0001

今日の環境

dockerをインストールする

Docker Desktop for Mac を公式ページからダウンロードして、インストールします。

たぶんDocker Composeも一緒にインストールされます。

Hello Worldをやってみる

以下のコマンドを実行します。

docker run --rm hello-world

コンテナ一覧を表示する

docker ps -a

gitリポジトリを作成して.gitignoreファイルを用意する | ubuntu18.04 + docker-compose + rails5 その0003

web_bonsaiリポジトリGitHubで作成してcloneする

Githubでプルダウンから Add .gitignore: Rails を選択してweb_bonsaiリポジトリを作成しました。

cloneして、ローカルにweb_bonsaiディレクトリができました。

GitHubで生成された.gitignoreファイルの記述内容

以下の通りでした。rails6に対応した.gitignoreファイルなんだろうなと思います。

*.rbc
capybara-*.html
.rspec
/db/*.sqlite3
/db/*.sqlite3-journal
/db/*.sqlite3-[0-9]*
/public/system
/coverage/
/spec/tmp
*.orig
rerun.txt
pickle-email-*.html

# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

# TODO Comment out this rule if you are OK with secrets being uploaded to the repo
config/initializers/secret_token.rb
config/master.key

# Only include if you have production secrets in this file, which is no longer a Rails default
# config/secrets.yml

# dotenv
# TODO Comment out this rule if environment variables can be committed
.env

## Environment normalization:
/.bundle
/vendor/bundle

# these should all be checked in to normalize the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc

# if using bower-rails ignore default bower_components path bower.json files
/vendor/assets/bower_components
*.bowerrc
bower.json

# Ignore pow environment settings
.powenv

# Ignore Byebug command history file.
.byebug_history

# Ignore node_modules
node_modules/

# Ignore precompiled javascript packs
/public/packs
/public/packs-test
/public/assets

# Ignore yarn files
/yarn-error.log
yarn-debug.log*
.yarn-integrity

# Ignore uploaded files in development
/storage/*
!/storage/.keep

web_bonsai/railsディレクトリを作成して.gitignoreを移動する

web_bonsaiディレクトリの中にrailsディレクトリを作成します。

$ mkdir rails

ファイルを移動します。

$ mv .gitignore rails/.gitignore

一旦addしてcommit

ファイルの移動だけで一旦コミットします。

web_bondai/.gitignoreを作成する

前回の記事で作成したprojectディレクトリ内ファイルとディレクトリをここに移動してくる想定で.gitignoreを作成します。

記述した内容は以下の通りです。

# root
docker-compose.yml

# https_portal
https_portal

# nginx
nginx/nginx.conf
nginx/log/nginx/access.log
nginx/log/nginx/error.log

# rails

一旦pushする

一旦pushして今回はここまでにしました。

ローカルでrailsのスタートページ表示までやってみる | ubuntu18.04 + docker-compose + rails5 その0002

参考にさせて頂いたページ

さくらメールボックス + gmail

docker-compose + rails5 + https

docker daemonの起動とか

dockerコマンドをsudo無しで実行する方法

sudo無しでdockerコマンドを実行できるようにする

以下のリンクは2つありますが、手順をひとつ試して上手くいかない場合には端末を再起動してみてから、もう一つの方法を試すといいかもしれません。

docker-compose をインストールする

公式ドキュメント通りやってみて上手くいかなかったら個人の記事に頼ります。

docker daemonの起動とか

docker daemonの起動とか、自動で起動する方法とかもここで押さえておくと良さそうです。

ディレクトリを作成して移動

mkdir project
cd project

docker-compose.ymlを作成

ファイルを作成します。

$ vim docker-compose.yml

自分のdocker-compose ymlの内容は下記の通りです。

version: '3'

services:
  https-portal:
    image: steveltn/https-portal:1
    ports:
      - 80:80
      - 443:443
    restart: always
    environment:
      DOMAINS: 'localhost -> http://nginx:8000'
      STAGE: local
    volumes:
      - ./https_portal/ssl_certs:/var/lib/https-portal
    depends_on:
      - nginx
  nginx:
    build: ./nginx
    ports:
      - "8000:8000"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/html:/var/www/html
      - ./nginx/log:/var/log
    depends_on:
      - web
  web:
    build: ./rails
    ports:
      - "3000:3000"
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - ./rails:/myapp
      - bundle:/usr/local/bundle
    environment:
      - RAILS_SERVE_STATIC_FILES=false
      - RAILS_ENV=development
volumes:
  bundle:

nginxディレクトリ作成

project ディレクトリ内に作成します。

$ mkdir nginx

nginx用のDockerfileを作成

$ vim nginx/Dockerfile

記述内容は以下の通りです。

FROM nginx:1.15.8

nginx/nginx.confを作成

$ vim nginx/nginx.conf

記述内容は以下の通りです。

user nginx;

events {
  # 1ワーカーの接続数
  # worker_connections 2048;

  # 複数のリクエストを同時に受け付けるか
  multi_accept on;

  # 複数アクセスをさばくためにI/O多重化に使うシステムコールを指定する
  use epoll;
}

http {
  # HTTPレスポンスヘッダのContent_Typeに付与する文字コード
  charset UTF-8;

  # HTTPレスポンスヘッダのServerにnginxのバージョンを入れるか(開発時以外は入れないほうが吉)
  server_tokens off;

  # upstreamのpumaを定義
  upstream puma {
    # server service名:3000; のように記述
    server web:3000;
  }

  # 
  server {
    # リスニングポート
    listen 8000;

    # ドメイン設定
    # server_name web-bonsai.com;
    server_name localhost

    # HTTPレスポンスヘッダのContent_Typeに付与する文字コード
    charset utf-8;

    # logの出力先
    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    # ドキュメントルート
    root /var/www/html;

    # location
    location /index.html {
      index index.html;
    }

    # location
    location / {
      #proxy_set_header X-CSRF-Token $http_x_csrf_token;
      #proxy_set_header X-Real-IP $remote_addr;
      proxy_pass http://puma;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_redirect off;
    }
  }
}

nginx/htmlディレクトリを作成

$ mkdir nginx/html

nginx/html/index.htmlの作成

$ vim nginx/html/index.html

記述内容は以下の通りです。

web_bonsai index.html

nginx/log/nginxディレクトリの作成

$ mkdir nginx/log
$ mkdir nginx/log/nginx

logファイルを空で作成

$ touch nginx/log/nginx/access.log
$ touch nginx/log/nginx/error.log

railsディレクトリを作成

これもprojectディレクトリで作成します。

$ mkdir rails

rails用のDockerfileを作成

$ vim rails/Dockerfile

記述内容は以下の通りです。

FROM ruby:2.6.3
ENV LANG C.UTF-8

RUN apt-get update -qq && apt-get install -y \
    build-essential \
    nodejs \
    sqlite3 \ 
 && rm -rf /var/lib/apt/lists/*

RUN gem install bundler

WORKDIR /tmp
ADD Gemfile Gemfile
ADD Gemfile.lock Gemfile.lock
RUN bundle install

ENV APP_HOME /myapp
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME
ADD . $APP_HOME

RUN mkdir -p tmp/sockets

rails/Gemfileを作成

$ vim rails/Gemfile

記述内容は以下の通りです。

source 'https://rubygems.org'

gem 'rails', '5.1.4'

rails/Gemfile.lockを作成

空のGemfile.lockを作成します。

$ touch rails/Gemfile.lock

コマンド実行

webサービスrails newします。

docker-compose run --rm web bundle exec rails new . --force --skip-bundle

docker-compose buildします。

docker-compose build

webサービスにbundle installしてgemをインストールします。

docker-compose run --rm web bundle install

docker-compose upします。初回は少し時間がかかります。

docker-compose up

このときhttps_portalディレクトリが作成されます。

以下の表示で止まりました。

db_1  | Version: '5.7.26'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)

ブラウザでアクセスしてみる

http://localhost:8000/ にブラウザでアクセスします。

sqlite3のエラーが表示された

以下のようなエラーが表示されていました。

Specified 'sqlite3' for database adapter, but the gem is not loaded. Add gem 'sqlite3' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

sqlite3のエラーを解消

rails5.1.x で起こるエラーがあるようなので、以下のようにGemfileを編集し、gemのバージョンを指定します。

#gem 'sqlite3'
gem 'sqlite3', '~> 1.3.6'

以下のコマンドでもう一度bundle installします。

docker-compose run --rm web bundle install

もう一度docker-compose upする

upします。

docker-compose up

もう一度ブラウザでアクセスしてみる

もう一度http://localhost:8000/ にブラウザでアクセスします。

今度は無事railsのスタートページが表示されました。

一度止める

別タブでprojectディレクトリまで移動して、以下のコマンドで止まります。

docker-compose down

ディレクトリとファイルの所有者変更

このままだとrails newによって生成されたファイルの所有者がrootなので、以下のような感じで所有者を変更すると編集しやすいと思います。

.gitディレクトリを削除

projectディレクトリに.gitディレクトリが作成されているので削除すると良いと思います。

任意のgitリポジトリで管理する

projectディレクトリを丸ごと任意のgitリポジトリにコミットすると楽だと思います。

今後サーバーを起動するとき

以下のように-dを付けてバックグラウンドで起動するのも良いと思います。

docker-compose up -d