build(docker): ensure build-stage packages installed with fresh apt metadata (#114)

* quick fix for failing image build

* build: optimize Dockerfile for smaller image and perms

- combine apt-get update and cleanup into single layer
- combine bundle install and bootsnap into one RUN
- copy build artifacts with --chown to set ownership
- create non-root rails user before copying files
This commit is contained in:
Himank Dave
2025-08-15 00:16:06 -04:00
committed by GitHub
parent 26c18427c7
commit d162c58732

View File

@@ -8,8 +8,9 @@ FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim AS base
WORKDIR /rails
# Install base packages
RUN apt-get update -qq && \
apt-get install --no-install-recommends -y curl libvips postgresql-client libyaml-0-2
RUN apt-get update -qq \
&& apt-get install --no-install-recommends -y curl libvips postgresql-client libyaml-0-2 \
&& rm -rf /var/lib/apt/lists /var/cache/apt/archives
# Set production environment
ARG BUILD_COMMIT_SHA
@@ -23,15 +24,15 @@ ENV RAILS_ENV="production" \
FROM base AS build
# Install packages needed to build gems
RUN apt-get install --no-install-recommends -y build-essential libpq-dev git pkg-config libyaml-dev
RUN apt-get update -qq \
&& apt-get install --no-install-recommends -y build-essential libpq-dev git pkg-config libyaml-dev \
&& rm -rf /var/lib/apt/lists /var/cache/apt/archives
# Install application gems
COPY .ruby-version Gemfile Gemfile.lock ./
RUN bundle install
RUN rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git
RUN bundle exec bootsnap precompile --gemfile -j 0
RUN bundle install \
&& rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git \
&& bundle exec bootsnap precompile --gemfile -j 0
# Copy application code
COPY . .
@@ -45,19 +46,15 @@ RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile
# Final stage for app image
FROM base
# Clean up installation packages to reduce image size
RUN rm -rf /var/lib/apt/lists /var/cache/apt/archives
# 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
useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash
USER 1000:1000
# Copy built artifacts: gems, application
COPY --chown=rails:rails --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}"
COPY --chown=rails:rails --from=build /rails /rails
# Entrypoint prepares the database.
ENTRYPOINT ["/rails/bin/docker-entrypoint"]