0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

webアプリ(Rails)をDocker化する方法

Last updated at Posted at 2023-11-06

はじめに

今回は、既存のwebアプリ(Rails)をDocker化する方法をまとめてみました。

条件

  • 今回は Docker composeを使用して環境構築します
    Docker composeとは、複数のコンテナを効率的に操作する為のツールです。
  • docker-compose up コマンドで rails severを起動し、http://localhost:3000でアクセスできるようにします

開発環境

  • Ruby:3.2.2
  • Ruby on Rails: 7.0.6
  • Postgres: 12

事前にDockerのインストールが必要です

1. リモートリポジトリ(docker-rails)をクローンしてローカルに持ってくる

$ git clone (docker-railsリポジトリのURL)
$ cd docker-rails

2. Dockefileを作成

$ touch Dockerfile

Dockerfileの中身を以下にする

# ベースイメージの選定
FROM ruby:3.2.2

# パッケージのインストールと更新
RUN apt-get update && apt-get install -y build-essential libpq-dev nodejs

WORKDIR /rails-docker

COPY Gemfile Gemfile.lock /rails-docker/

# Gemをインストールするコマンド
RUN bundle install

ADD . /rails-docker

3. docker-compose.ymlを作成

$ touch docker-compose.yml
docker-compose.yml
# バージョンを選定
version: '3'

services:
# dbコンテナ
  db:
    image: postgres:12
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    volumes:
      - postgresql-data:/var/lib/postgresql/data

# webコンテナ
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    ports:
      - '3000:3000'
    volumes:
      - '.:/rails-docker'
    depends_on:
      - db
volumes:
  postgresql-data:
    driver: local

4. database.ymlを編集する

database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password: postgres
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: myapp_development

5. コンテナを作成し、起動する

docker image を作成します

$ docker-compose build

コンテナの作成、起動する

$ docker-compose up -d

データベースの作成

先ほどつくったコンテナの中に入る

$ docker-compose exec web bash

Railsのデータベースを作成する

$ rails db:create
$ rails db:migrate
$ exit

6. ブラウザでhttp://localhost:3000にアクセスする

設定が完了したので、アプリを起動して確認します。

$ docker-compose up

http://localhost:3000にアクセスして。アプリがきちんと表示されれば完了です!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?