Stan Blog

學習過程中的一些記錄

[Docker] 使用 docker-compose dockerize rails 專案

1. 建立基本檔案

create Dockerfile, docker-compose.yml, Gemfile, Gemfile.lock, entrypoint.sh

填入

### Dockerfile

FROM ruby:2.5
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"]
### docker-compose

version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
  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
### Gemfile

source 'https://rubygems.org'
gem 'rails', '~>5'
### 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 "$@"

2. 執行 rails new

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

3. 建立 docker image

docker-compose build

4. 執行 docker

docker-compose up

5. 建立 db

docker ps
docker exec -it {container id} /bin/bash

docker-compose run web rake db:create

6. 完成

localhost:3000 可以看到 rails 預設歡迎頁面


Ref:

Comments

comments powered by Disqus