Rails7、sqlite3 和 litestream组合Docker配置

22-01-01 banq

rails7、sqlite3 和 litestream 在一起非常棒。我把我所有的迷你 webapps 都换成了它。这是你见过的最简单的生产设置。这个 docker 文件是将 Rails 应用程序投入生产所需的全部内容:

# Rails production setup via SQLite3 made durable by https://litestream.io/ 
# Copy this to Dockerfile on a fresh rails app. Deploy to fly.io or any other container engine. 
#  try locally: docker build . -t rails && docker run -p3000:3000 -it rails
#  in production you might want to map /data to somewhere on the host, 
#  but you don't have to!
FROM ruby:3.0.2

# use https://github.com/benbjohnson/litestream/releases/download/v0.3.7/litestream-v0.3.7-linux-amd64-static.tar.gz on intel
ADD https://github.com/benbjohnson/litestream/releases/download/v0.3.7/litestream-v0.3.7-linux-arm64-static.tar.gz /tmp/litestream.tar.gz
RUN tar -C /usr/local/bin -xzf /tmp/litestream.tar.gz

ENV RAILS_ENV 'production'
ENV DB_PATH '/data/production.sqlite3'

# find a REPLICA_URL host/keys setup for persisting your sqlite3 database ( https://litestream.io/guides/ )
# supports sftp, s3, azure, google cloud storage, backblaze, etc. you probably have an account 
# already 
ENV REPLICA_URL 's3://<your-url>/db.sqlite3'
ENV LITESTREAM_ACCESS_KEY_ID '<your-access-key-id>'
ENV LITESTREAM_SECRET_ACCESS_KEY '<your-secret-access-key>'

# get dependencies
ADD Gemfile /app/
ADD Gemfile.lock /app/
RUN bundle install

# add code (and bundle)
ADD . /app
RUN bundle exec rake assets:precompile

# rails expects production.sqlite3 to be in db/production.sqlite3
RUN ln -nfs $DB_PATH /app/db/production.sqlite3


  # if the db file doesn't exist we get it from the REPLICA_URL
  [ ! -f $DB_PATH ] && litestream restore -v -if-replica-exists -o $DB_PATH "${REPLICA_URL}" \
  # then we run the migrations
  ; bundle exec rake db:migrate \
  # then we launch replicate and execute rails server
  ; litestream replicate -exec "bundle exec rails server -p 3000" $DB_PATH $REPLICA_URL