LoginSignup
0
0

More than 1 year has passed since last update.

Docker composeを使ったWebアプリ開発環境の構築

Last updated at Posted at 2023-02-13

Rails開発用のDockerfileを作成する

dsfklj.png

Dockerfile
FROM ruby:2.5
RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    nodejs \
    postgresql-client \
    yarn
WORKDIR /product-register
COPY Gemfile Gemfile.lock /product-register/
RUN bundle install
Gemfile
source 'https://rubygems.org'
gem 'rails', '~>5.2'

Dockerfileの中身

FROM ruby2.5

rubyというイメージのver2.5を使う

RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    nodejs \
    postgresql-client \
    yarn

必要なパッケージをインストールする

WORKDIR /product-register

product-registerというフォルダをホスト側に作っているので
コンテナ側にもルート直下でproduct-registerを作っておいて
そこをワークディレクトリとして作業していく

COPY Gemfile Gemfile.lock /product-register/
RubyのイメージにはRailsは無い!!

ホストで作ったGemfileを使ってRailsをインストールする!!
ホストで作ったGemfileをコンテナにコピーする!!

RUN bundle install

コンテナにGemfileが出来るのでbundle installというコマンドを実行する

必要なパッケージが分からない!!

  • コンテナを立てて、Railsを起動してみて何かエラーが出る度にパッケージをインストールすれば良い!!

  • 実際にはパッケージをインストールする部分は && で繋げるのではなく、RUNで1個1個書いていく!!

  • Railsを起動してエラーが出る度に追加する!!

  • xxx, yyyをインストールする -> Rails起動 -> エラー発生!!

    解決法がzzzをインストールする -> zzzというパッケージをインストールする

Dockerfile
RUN apt-get update
RUN apt-get install -y xxx
RUN apt-get install -y yyy
RUN apt-get install -y zzz
ある時点でエラーが出ず、自分のアプリがきちんと動く事が確認出来たら && で繋げる!!
$ docker build .
エラー発生!!

error.png

Unable to locate package libpa-dev
Dockerfile
FROM ruby:2.5
RUN apt-get update && apt-get install -y \
    build-essential \
    libpa-dev \
    nodejs \
    postgresql-client \
    yarn
WORKDIR /product-register
COPY Gemfile Gemfile.lock /product-register/
RUN bundle install

libpa-devというパッケージは無い!!
=> libpq-devに修正する!!

再度、docker build . する!!
dfkjsl.png

docker-compose.ymlの書き方

こんな時にDocker-composeと使う!!
  • $docker runコマンドが長くなるとき
  • 複数のコンテナをまとめて起動する時
docker-compose.yml
version: '3'

services:
  web:
    build:.
    ports:
        -'3000:3000'
    volumes:
      - '.:product-register'
    tty:true
    stdin_open:true
ymlの書き方は基本的にkeyとvalueの組み合わせで書く
key:value


書いてある内容:
version: '3'

docker-composeのバージョンを指定する

services:
  web:
    build:.
    ports:
        -'3000:3000'
    volumes:
      - '.:product-register'
    tty:true
    stdin_open:true

services:

serviceを複数入れるための親のキー

 web:
    build:.
    ports:
        -'3000:3000'
    volumes:
      - '.:product-register'
    tty:true
    stdin_open:true

webのサービスに対するパラメータを書いている!!

コンテナを起動する時にどんなパラメータを使うのかを書いている!!
docker run で指定していたオプションを書いている!!
build: .

docker build の情報を書いている。


ports:
 -'3000:3000'

ポートを指定している


volumes: 
    - '.:/product-register'

コンテナ内でも使うホストのファイルを指定する

相対パスで指定する!!
tty:true
stdin_open:true

$ docker run -itの-itというオプションと同じ役割

Railsのセットアップ

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