在安装pg(X.X.X)时发生了一个错误,Bundler无法继续。请解决此问题
背景 – 背景情况
在使用Docker创建Rails和PostgreSQL开发环境时遇到的错误。
我本打算去构建,但在安装pg的gem时发生了错误,无法完成构建。
环境 –
Ruby(3.2.2), Rails(7.1.1), Docker, PostgreSQL → Ruby(3.2.2), Rails(7.1.1), Docker, PostgreSQL
发生的情况
在Rails 7.1中,会自动生成Dockerfile,所以我基本上打算以此为基础进行构建。
由于计划中的数据库不是SQLite3而是PostgreSQL,
因此需要添加”pg”这个gem。
# syntax = docker/dockerfile:1
# Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile
ARG RUBY_VERSION=3.2.2
FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base
# Rails app lives here
WORKDIR /rails
# Set production environment
ENV RAILS_ENV="production" \
BUNDLE_DEPLOYMENT="1" \
BUNDLE_PATH="/usr/local/bundle" \
BUNDLE_WITHOUT="development"
# Throw-away build stage to reduce size of final image
FROM base as build
# Install packages needed to build gems
RUN apt-get update -qq && \
apt-get install --no-install-recommends -y build-essential git libvips pkg-config
# Install application gems
COPY Gemfile Gemfile.lock ./
RUN bundle install && \
rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \
bundle exec bootsnap precompile --gemfile
# Copy application code
COPY . .
# Precompile bootsnap code for faster boot times
RUN bundle exec bootsnap precompile app/ lib/
# Precompiling assets for production without requiring secret RAILS_MASTER_KEY
RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile
# Final stage for app image
FROM base
# Install packages needed for deployment
RUN apt-get update -qq && \
apt-get install --no-install-recommends -y curl libsqlite3-0 libvips && \
rm -rf /var/lib/apt/lists /var/cache/apt/archives
# Copy built artifacts: gems, application
COPY --from=build /usr/local/bundle /usr/local/bundle
COPY --from=build /rails /rails
# Run and own only the runtime files as a non-root user for security
RUN useradd rails --create-home --shell /bin/bash && \
chown -R rails:rails db log storage tmp
USER rails:rails
# Entrypoint prepares the database.
ENTRYPOINT ["/rails/bin/docker-entrypoint"]
# Start the server by default, this can be overwritten at runtime
EXPOSE 3000
CMD ["./bin/rails", "server"]
发生的事件
当进行build时,执行bundle install时,安装”pg”模块失败。
错误内容(摘要)
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
Unable to find PostgreSQL client library.
An error occurred while installing pg (1.5.4), and Bundler cannot continue.
In Gemfile: pg
解决方案
通过在包中添加libpq-dev解决了这个问题。
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
libpq-dev是一个包含PostgreSQL客户端头文件和库的软件包,似乎是为了开发目的而安装PostgreSQL所必需的。
实际上,在这个漫长的日志中有一些提示。由于我错过了它们,花了一些时间,所以我感到后悔。。
Please install libpq or postgresql client package like so:
sudo apt install libpq-dev
sudo yum install postgresql-devel
sudo zypper in postgresql-devel
sudo pacman -S postgresql-libs
給你一個額外的禮物
我会附上一些有助于理解Docker概念和机制的资料。虽然有96页并且内容很多,但因为有图表和插图来解释机制,所以很容易在脑海中形成想象。