容器化 Ruby on Rails 應用程式

先決條件

  • 您已安裝最新版本的 Docker Desktop
  • 您已安裝 Git 客戶端。本節中的示例展示了 Git CLI,但您可以使用任何客戶端。

概述

本節將引導您完成 Ruby on Rails 應用程式的容器化和執行。

從 Rails 7.1 開始,Docker 已原生支援。這意味著當您建立新的 Rails 應用程式時,系統將為您生成 `Dockerfile`、`.dockerignore` 和 `bin/docker-entrypoint` 檔案。

如果您有一個現有的 Rails 應用程式,您將需要手動建立 Docker 資產。不幸的是,`docker init` 命令尚不支援 Rails。這意味著如果您正在使用 Rails,您將需要手動從以下示例中複製 Dockerfile 和其他相關配置。

1. 初始化 Docker 資產

Rails 7.1 原生生成多階段 Dockerfile,下面是根據 Rails 模板生成的檔案示例。

多階段 Dockerfile 透過分離構建和執行時依賴項來幫助建立更小、更高效的映象,確保最終映象中只包含必要的元件。有關更多資訊,請參閱多階段構建指南

儘管 Dockerfile 是自動生成的,但瞭解其目的和功能非常重要。強烈建議查閱以下示例。

Dockerfile
# syntax=docker/dockerfile:1
# check=error=true

# This Dockerfile is designed for production, not development.
# docker build -t app .
# docker run -d -p 80:80 -e RAILS_MASTER_KEY=<value from config/master.key> --name app app

# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html

# Make sure RUBY_VERSION matches the Ruby version in .ruby-version
ARG RUBY_VERSION=3.3.6
FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base

# Rails app lives here
WORKDIR /rails

# Install base packages
# Replace libpq-dev with sqlite3 if using SQLite, or libmysqlclient-dev if using MySQL
RUN apt-get update -qq && \
    apt-get install --no-install-recommends -y curl libjemalloc2 libvips libpq-dev && \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# Set production environment
ENV RAILS_ENV="production" \
    BUNDLE_DEPLOYMENT="1" \
    BUNDLE_PATH="/usr/local/bundle" \
    BUNDLE_WITHOUT="development"

# Throw-away build stage to reduce size of final image
FROM base AS build

# Install packages needed to build gems
RUN apt-get update -qq && \
    apt-get install --no-install-recommends -y build-essential curl git pkg-config libyaml-dev && \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# Install JavaScript dependencies and Node.js for asset compilation
#
# Uncomment the following lines if you are using NodeJS need to compile assets
#
# ARG NODE_VERSION=18.12.0
# ARG YARN_VERSION=1.22.19
# ENV PATH=/usr/local/node/bin:$PATH
# RUN curl -sL https://github.com/nodenv/node-build/archive/master.tar.gz | tar xz -C /tmp/ && \
#     /tmp/node-build-master/bin/node-build "${NODE_VERSION}" /usr/local/node && \
#     npm install -g yarn@$YARN_VERSION && \
#     npm install -g mjml && \
#     rm -rf /tmp/node-build-master

# Install application gems
COPY Gemfile Gemfile.lock ./
RUN bundle install && \
    rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \
    bundle exec bootsnap precompile --gemfile

# Install node modules
#
# Uncomment the following lines if you are using NodeJS need to compile assets
#
# COPY package.json yarn.lock ./
# RUN --mount=type=cache,id=yarn,target=/rails/.cache/yarn YARN_CACHE_FOLDER=/rails/.cache/yarn \
#     yarn install --frozen-lockfile

# Copy application code
COPY . .

# Precompile bootsnap code for faster boot times
RUN bundle exec bootsnap precompile app/ lib/

# Precompiling assets for production without requiring secret RAILS_MASTER_KEY
RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile

# Final stage for app image
FROM base

# Copy built artifacts: gems, application
COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}"
COPY --from=build /rails /rails

# Run and own only the runtime files as a non-root user for security
RUN groupadd --system --gid 1000 rails && \
    useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \
    chown -R rails:rails db log storage tmp
USER 1000:1000

# Entrypoint prepares the database.
ENTRYPOINT ["/rails/bin/docker-entrypoint"]

# Start server via Thruster by default, this can be overwritten at runtime
EXPOSE 80
CMD ["./bin/thrust", "./bin/rails", "server"]

上面的 Dockerfile 假定您將 Thruster 與 Puma 一起用作應用程式伺服器。如果您使用任何其他伺服器,您可以將最後三行替換為以下內容

# Start the application server
EXPOSE 3000
CMD ["./bin/rails", "server"]

此 Dockerfile 使用位於 `./bin/docker-entrypoint` 的指令碼作為容器的入口點。此指令碼準備資料庫並執行應用程式伺服器。以下是此類指令碼的示例。

docker-entrypoint
#!/bin/bash -e

# Enable jemalloc for reduced memory usage and latency.
if [ -z "${LD_PRELOAD+x}" ]; then
    LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit)
    export LD_PRELOAD
fi

# If running the rails server then create or migrate existing database
if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then
  ./bin/rails db:prepare
fi

exec "${@}"

除了上面兩個檔案之外,您還需要一個 `.`dockerignore 檔案。此檔案用於從構建上下文中排除檔案和目錄。下面是 `.`dockerignore 檔案的示例。

.dockerignore
# See https://docs.docker.net.tw/engine/reference/builder/#dockerignore-file for more about ignoring files.

# Ignore git directory.
/.git/
/.gitignore

# Ignore bundler config.
/.bundle

# Ignore all environment files.
/.env*

# Ignore all default key files.
/config/master.key
/config/credentials/*.key

# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

# Ignore pidfiles, but keep the directory.
/tmp/pids/*
!/tmp/pids/.keep

# Ignore storage (uploaded files in development and any SQLite databases).
/storage/*
!/storage/.keep
/tmp/storage/*
!/tmp/storage/.keep

# Ignore assets.
/node_modules/
/app/assets/builds/*
!/app/assets/builds/.keep
/public/assets

# Ignore CI service files.
/.github

# Ignore development files
/.devcontainer

# Ignore Docker-related files
/.dockerignore
/Dockerfile*

您可能需要的最後一個可選檔案是 `compose.yaml` 檔案,Docker Compose 使用它來定義構成應用程式的服務。由於使用的是 SQLite 資料庫,因此無需為資料庫定義單獨的服務。唯一需要的服務是 Rails 應用程式本身。

compose.yaml
services:
  web:
    build: .
    environment:
      - RAILS_MASTER_KEY
    ports:
      - "3000:80"

您的應用程式資料夾中現在應該有以下檔案

  • .dockerignore
  • compose.yaml
  • Dockerfile
  • bin/docker-entrypoint

要了解有關這些檔案的更多資訊,請參閱以下內容

2. 執行應用程式

要執行應用程式,請在應用程式目錄中的終端中執行以下命令。

$ RAILS_MASTER_KEY=<master_key_value> docker compose up --build

開啟瀏覽器並訪問 https://:3000 檢視應用程式。您應該會看到一個簡單的 Ruby on Rails 應用程式。

在終端中,按 ctrl+c 停止應用程式。

3. 在後臺執行應用程式

您可以透過新增 `-d` 選項使應用程式脫離終端執行。在 `docker-ruby-on-rails` 目錄中,在終端中執行以下命令。

$ docker compose up --build -d

開啟瀏覽器,在 https://:3000 檢視應用程式。

您應該會看到一個簡單的 Ruby on Rails 應用程式。

在終端中,執行以下命令以停止應用程式。

$ docker compose down

有關 Compose 命令的更多資訊,請參閱Compose CLI 參考

摘要

在本節中,您學習瞭如何使用 Docker 容器化並執行 Ruby 應用程式。

相關資訊

後續步驟

在下一節中,您將瞭解如何使用 GitHub Actions 設定 CI/CD 管道。