使用Docker在(M1芯片)上运行Rails

简介

我在搭载M1芯片的MacBook上尝试了在Docker上搭建rails6的过程。下面是成功时的步骤记录。

前提信息

M1MacBook

Docker Desktop for Apple silicon Version 4.15.0

ruby-3.1.2

构建过程的笔记

创建应用程序目录

mkdir railsapp
cd railsapp

准备基本文件

touch Dockerfile
touch Gemfile
touch Gemfile.lock
touch docker-compose.yml
touch entrypoint.sh

./Dockerfile 的中文释义可以是「Docker文件」。

FROM ruby:3.1.2
RUN apt-get update -qq && apt-get install -y build-essential nodejs postgresql-client libpq-dev

RUN apt-get update && apt-get install -y curl apt-transport-https wget && \
wget --quiet -O - /tmp/pubkey.gpg https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && apt-get install -y yarn

# install nodejs(LTS)
RUN curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - && apt-get install -y nodejs

RUN mkdir /railsapp
WORKDIR /railsapp
COPY Gemfile /railsapp/Gemfile
COPY Gemfile.lock /railsapp/Gemfile.lock
RUN bundle install
COPY . /railsapp

COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]

./Gemfile 可以进行重述为:“Gemfile文件”。

source "https://rubygems.org"
gem "rails", "~>6"

./docker-compose.yml 的中文本地化版本。

version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data    
    environment:
      POSTGRES_HOST_AUTH_METHOD: 'trust'    

  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/railsapp
    ports:
      - "3000:3000"
    depends_on:
      - db

执行脚本入口文件 “entrypoint.sh”。

#!/bin/bash
set -e

rm -f /railsapp/tmp/pids/server.pid

exec "$@"

创建一个Rails项目

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

建立

docker-compose build

记录DB的基本信息

./config/database.yml的翻译:
./配置/数据库.yml.

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

development:
  <<: *default
  database: railsapp_development

实际运用时,请勿明文编写密码,最好使用最少限度的gem ‘dotenv-rails’等工具来管理密码,并将其放在.env文件中(进行.ignore处理)。

password: <%= ENV['APP_DBPASS'] %> 

借助这种方式进行运作

创建数据库

docker-compose run web rake db:create

安装webpack。

docker-compose run web rails webpacker:install

进行上载并进行操作确认

docker-compose up
http://localhost:3000/

参考阅读

 

已解决的部分(已在上述中反映)

更新GPG(GNU Privacy Guard)的密钥部分。

gpg: no valid OpenPGP data found.

请参考以下链接进行更新:https://zenn.dev/junki555/articles/2de6024a191913

将Ruby和nodejs的兼容版本进行调整。

起初有Nokogiri错误,我参考了下面的文章进行了尝试,最终通过更改Ruby和Node.js版本解决了问题。
https://regardie.dev/post-5126

除此之外

gem "net-smtp"

也许可以加上。