Rails7、sqlite3 和 litestream組合Docker配置

banq發表於2022-01-01

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
WORKDIR /app
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

EXPOSE 3000

CMD \
  # 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


 

相關文章