my blog
1# syntax = docker/dockerfile:1
2
3# Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile
4ARG RUBY_VERSION=3.0.2
5FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base
6
7# Rails app lives here
8WORKDIR /rails
9
10# Set production environment
11ENV RAILS_ENV="production" \
12 BUNDLE_DEPLOYMENT="1" \
13 BUNDLE_PATH="/usr/local/bundle" \
14 BUNDLE_WITHOUT="development"
15
16
17# Throw-away build stage to reduce size of final image
18FROM base as build
19
20# Install packages needed to build gems
21RUN apt-get update -qq && \
22 apt-get install --no-install-recommends -y build-essential git libvips pkg-config
23
24# Install application gems
25COPY Gemfile Gemfile.lock ./
26RUN bundle install && \
27 rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \
28 bundle exec bootsnap precompile --gemfile
29
30# Copy application code
31COPY . .
32
33# Precompile bootsnap code for faster boot times
34RUN bundle exec bootsnap precompile app/ lib/
35
36# Precompiling assets for production without requiring secret RAILS_MASTER_KEY
37RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile
38
39
40# Final stage for app image
41FROM base
42
43# Install packages needed for deployment
44RUN apt-get update -qq && \
45 apt-get install --no-install-recommends -y curl libsqlite3-0 libvips && \
46 rm -rf /var/lib/apt/lists /var/cache/apt/archives
47
48# Copy built artifacts: gems, application
49COPY --from=build /usr/local/bundle /usr/local/bundle
50COPY --from=build /rails /rails
51
52# Run and own only the runtime files as a non-root user for security
53RUN useradd rails --create-home --shell /bin/bash && \
54 chown -R rails:rails db log storage tmp
55USER rails:rails
56
57# Entrypoint prepares the database.
58ENTRYPOINT ["/rails/bin/docker-entrypoint"]
59
60# Start the server by default, this can be overwritten at runtime
61EXPOSE 3000
62CMD ["./bin/rails", "server"]