知り合いと飲んだ勢いで、簡単なwebアプリを作成することになったので、
開発環境として、docker docsのRails+Postgresのサンプルを元に、
開発環境を作成してみたら、簡単にできたので、投稿してみました。
プロジェクトのディレクトリを作成する
directory
/hoge_project
Dockerfile
を作成する
directory
/hoge_project
|_ Dockerfile
Dockerfile
FROM ruby:2.6.3
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
# 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
# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]
Gemfile
を作成する
directory
/hoge_project
|_ Dockerfile
|_ Gemfile
Gemfile
source 'https://rubygems.org'
gem 'rails', '5.2.3'
Gemfile.lock
を作成する
directory
/hoge_project
|_ Dockerfile
|_ Gemfile
|_ Gemfile.lock
entrypoint.sh
を作成する
directory
/hoge_project
|_ Dockerfile
|_ Gemfile
|_ Gemfile.lock
|_ entrypoint.sh
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 "$@"
server.pid
があるかないかでサーバーを再起動させないようにするらしい
(うん、よくわからん…)
docker-compose.yml
を作成する
directory
/hoge_project
|_ Dockerfile
|_ Gemfile
|_ Gemfile.lock
|_ entrypoint.sh
|_ docker-compose.yml
docker-compose.yml
version: '3'
services:
db:
image: postgres:12
volumes:
- ./tmp/db:/var/lib/postgresql/data
ports:
- "8000:5432"
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
doker docs
でのサンプルではpostgres
のポートが明示的に設定されていないので、
下記のように追加しました。
ports:
- "8000:5432"
docker-compose run
でプロジエクトを作成する
下記のコマンドを実行すると...
sh
$ docker-compose run web rails new . --force --no-deps --database=postgresql
プロジェクトができる!!!
directory
/hoge_project
|_ app
|_ bin
|_ config
|_ db
|_ lib
|_ log
|_ public
|_ storage
|_ test
|_ tmp
|_ vendor
|_ .gitignore
|_ .ruby-version
|_ config.ru
|_ docker-compose.yml
|_ Dockerfile
|_ entrypoint.sh
|_ Gemfile
|_ Gemfile.lock
|_ package.json
|_ Rakefile
|_ README.md
Gemfile
が更新されたので、再度、イメージを作成する
sh
$ docker-compose build
作成するデータベースと向き先を変更する
config/database.yml
default: &default
adapter: postgresql
encoding: unicode
host: db
username: postgres
password:
pool: 5
development:
<<: *default
database: myapp_development
test:
<<: *default
database: myapp_test
docker-compose up
でコンテナを起動する
sh
$ docker-compose up
データベースを作成する
sh
$ docker-compose run web rake db:create
アクセスできるか、確認する
Rails
http://localhost:3000
PostgreSQL
host:localhost
port:8000
Database:myapp_development
user:postgres
password:
終わり
簡単に動くものなら、意外と簡単にできるので、
みなさんもやってみてください〜