This page looks best with JavaScript enabled
⚠️

【Docker】いつかのdocker-compose

 ·   ·  ☕ 1 分で読めます
✏️

環境

Rails
PostgreSQL

設定ファイル

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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'"
    # 下二行でbinding.pryを使えるようにする
    tty: true
    stdin_open: true
    volumes:
      # 同期する。ローカル:Docker内
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
FROM ruby:2.6.6
# タイムゾーンの設定
ENV TZ='Asia/Tokyo'
RUN apt-get update -qq \
  && apt-get install -y nodejs postgresql-client \
  # 日本語をDocker内で使えるようにする
  && apt-get install -y locales \
  && locale-gen C.UTF-8 \
  && echo "export LANG=C.UTF-8" >> ~/.bashrc
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"]
1
2
3
4
5
6
7
8
#!/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 "$@"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  # POSTGRES_PASSWORD: password と同じにする
  password: password
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

# 略

コマンド

セットアップ

1
2
3
4
5
$ docker-compose build
$ docker-compose up -d
$ docker-compose run web rails db:create
$ docker-compose run web rails db:migrate
$ docker-compose run web rails db:seed
1
$ docker-compose run web # コマンド

開発時によく使うコマンド

1
2
3
$ docker container ls
$ docker exec -it <container id> bash # コンテナの中に入れる。中でrails cをしたり
$ docker attach <container id> # デーモン化したコンテナの中に入る。ログが流れる。binding.pryはここが止まる

テスト実行

1
$ docker-compose run web rspec
Share on

END
END
@aiandrox

 
目次