Невозможно развернуть приложение Rails в Google Cloud Run - PullRequest
0 голосов
/ 24 октября 2019

У меня есть приложение Rails, работающее локально с Docker, и сейчас я пытаюсь развернуть его на Google Cloud Platform с помощью Cloud Run, следуя этому замечательному учебнику Лорана Жулиарда.

IИспользую следующие службы GCP:

  • Cloud Build для создания образа контейнера.
  • Cloud Run для развертывания.
  • Облачное хранилище для Rails Active Storage.
  • Облачное SQL для моей базы данных Postgres.
  • Управление ключами облакаСлужба для моих секретов.

Последние 3 службы не имеют отношения к данной проблеме (я думаю ??‍♂️).

Мой процесс развертывания состоит из 2 шагов:

  1. Построение образа контейнера с помощью Cloud Build
  2. Развертывание образа с помощью Cloud Run

Построение контейнераИзображение с использованием Cloud Build

cloudbuild.yaml Файл описывает шаги, которые Cloud Build должен пройти, чтобы построить свой контейнер.

steps:

# Decrypt Rails Master key file
- name: gcr.io/cloud-builders/gcloud
  args: ["kms", "decrypt", "--ciphertext-file=./config/master.key.enc", 
         "--plaintext-file=./config/master.key",
         "--location=us-central1","--keyring=whale-on-rails", 
        "--key=rails_master_key"]

# Decrypt Whale on Rails service account credentials
- name: gcr.io/cloud-builders/gcloud
  args: ["kms", "decrypt", "--ciphertext-file=./config/whale_on_rails.key.enc", 
         "--plaintext-file=./config/whale_on_rails.key",
         "--location=us-central1","--keyring=whale-on-rails", 
         "--key=whale_on_rails_key"]

# Build image with tag 'latest' and pass decrypted Rails DB password as argument
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build',
    '--tag', 'gcr.io/$PROJECT_ID/whale_on_rails:latest',
    '--build-arg', 'DB_PWD',
    '--build-arg', 'RUBY_VERSION=${_RUBY_VERSION}',
    '--build-arg', 'PG_MAJOR=${_PG_MAJOR}',
    '--build-arg', 'NODE_MAJOR=${_NODE_MAJOR}',
    '--build-arg', 'YARN_VERSION=${_YARN_VERSION}',
    '--build-arg', 'BUNDLER_VERSION=${_BUNDLER_VERSION}',
    '--build-arg', 'RAILS_ENV=${_RAILS_ENV}',
    '--build-arg', 'REDIS_URL=${_REDIS_URL}',
    '--build-arg', 'DATABASE_HOST=${_DATABASE_HOST}',
    '--build-arg', 'DATABASE_USER=${_DATABASE_USER}',
    '--build-arg', 'DATABASE_NAME=${_DATABASE_NAME}',
    '.'
  ]
  secretEnv: ['DB_PWD']
  env:
    - RAILS_ENV=${_RAILS_ENV}
    - REDIS_URL=redis://redis:6379/
    - DATABASE_HOST=/cloudsql/whale-on-rails:us-central1:whale-on-rails-production
    - DATABASE_USER=postgres
    - DATABASE_NAME=whale-on-rails

# Push new image to Google Cloud Registry       
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/$PROJECT_ID/whale_on_rails:latest']

secrets:
- kmsKeyName: projects/whale-on-rails/locations/us-central1/keyRings/whale-on-rails/cryptoKeys/db_pwd_key
  secretEnv:
    DB_PWD: "CiQArHLfBqlON9MNzM+eKp/Un/HJucmgUftgl5LkYBzvLjsXsaQSOQCBzWJBAh061i7dJrNhEQeWqJHgSkaJpRka9w9nxmbiFzHZ1fpXOm0d7FWAi/8v36EDXmWnxkYXsw=="

substitutions:
  _RUBY_VERSION: '2.6.5'
  _PG_MAJOR: '11'
  _NODE_MAJOR: '12'
  _YARN_VERSION: '1.13.0'
  _BUNDLER_VERSION: '2.0.2'
  _RAILS_ENV: production
  _REDIS_URL: redis://redis:6379/
  _DATABASE_HOST: /cloudsql/whale-on-rails:us-central1:whale-on-rails-production
  _DATABASE_USER: postgres
  _DATABASE_NAME: whale-on-rails

Dockerfile : этот файл вызывается с помощью шага 'Build image' в Cloud Build.

ARG RUBY_VERSION
FROM ruby:$RUBY_VERSION

ARG PG_MAJOR
ARG NODE_MAJOR
ARG BUNDLER_VERSION
ARG YARN_VERSION
ARG RAILS_ENV

# Add PostgreSQL to sources list
RUN curl -sSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - \
  && echo 'deb http://apt.postgresql.org/pub/repos/apt/ stretch-pgdg main' $PG_MAJOR > /etc/apt/sources.list.d/pgdg.list

# Add NodeJS to sources list
RUN curl -sL https://deb.nodesource.com/setup_$NODE_MAJOR.x | bash -

# Add Yarn to the sources list
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
  && echo 'deb http://dl.yarnpkg.com/debian/ stable main' > /etc/apt/sources.list.d/yarn.list

# Install dependencies
COPY .docker/dev/Aptfile /tmp/Aptfile
RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get -yq dist-upgrade && \
  DEBIAN_FRONTEND=noninteractive apt-get install -yq --no-install-recommends \
    build-essential \
    postgresql-client-$PG_MAJOR \
    nodejs \
    yarn=$YARN_VERSION-1 \
    $(cat /tmp/Aptfile | xargs) && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
    truncate -s 0 /var/log/*log

# Create a directory for the app code
ENV APP_HOME=/usr/src/app
# RUN mkdir -p ${APP_HOME}
WORKDIR ${APP_HOME}

# Install production dependencies (Gems installation in
# local vendor directory)
COPY Gemfile Gemfile.lock ./
ENV BUNDLE_FROZEN=true
# Upgrade RubyGems and install required Bundler version 
RUN gem update --system && \
    gem install bundler:$BUNDLER_VERSION
RUN bundle install

ENV RAILS_ENV=$RAILS_ENV
ENV RAILS_SERVE_STATIC_FILES=true
ENV RAILS_LOG_TO_STDOUT=true

COPY . .

# Pre-compile Rails assets (master key needed)
RUN yarn install
RUN RAILS_ENV=production bundle exec rails assets:precompile

# Set Google App Credentials environment variable with Service Account
ENV GOOGLE_APPLICATION_CREDENTIALS=${APP_HOME}/config/whale_on_rails.key

# Database environment variables
ARG DATABASE_NAME
ARG DATABASE_HOST
ARG DATABASE_USER
ARG DB_PWD
ENV DATABASE_PASSWORD=$DB_PWD
ENV DATABASE_NAME=$DATABASE_NAME
ENV DATABASE_HOST=$DATABASE_HOST
ENV DATABASE_USER=$DATABASE_USER

RUN chmod +x ${APP_HOME}/.docker/script/entry
ENTRYPOINT ["/usr/src/app/.docker/script/entry"]

точка входа

#!/usr/bin/env bash

cd /usr/src/app

# Create, migrate and seed the Rails production DB
bundle exec rails db:prepare

# Do some protective cleanup
> log/production.log
rm -f tmp/pids/server.pid

# Run the web service on container startup
bundle exec rails server -e production -b 0.0.0.0 -p $PORT

Наконец, я использую следующую командупостроить контейнер.

$ gcloud builds submit --config cloudbuild.yaml

Этот процесс прекрасно работает. Проблема заключается в следующем шаге ...

Развернуть образ с помощью Cloud Run

$ gcloud beta run deploy whale-on-rails --image gcr.io/$PROJECT_ID/whale_on_rails \                                                                                              4m 58s Ruby 2.6.5
  --set-cloudsql-instances whale-on-rails-production \
  --region us-central1 --allow-unauthenticated --platform managed

На этом шаге я получаю эту ошибку в терминале:

ERROR: (gcloud.beta.run.deploy) Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.

И, проверяя журналы Cloud Run, я получаю следующее:

2019-10-24 13:03:35.448 CEST<main>: warning: timer_create failed: Success, signals racy
2019-10-24 13:03:37.756 CEST=> Booting Puma
2019-10-24 13:03:37.756 CEST=> Rails 6.0.0 application starting in production
2019-10-24 13:03:37.756 CEST=> Run `rails server --help` for more startup options
2019-10-24 13:03:40.687 CESTExiting
2019-10-24 13:03:40.687 CEST(erb):21:in `<main>': undefined local variable or method `“config' for main:Object (NameError)
2019-10-24 13:03:40.687 CEST from /usr/local/lib/ruby/2.6.0/erb.rb:901:in `eval'
2019-10-24 13:03:40.687 CEST from /usr/local/lib/ruby/2.6.0/erb.rb:901:in `result'
2019-10-24 13:03:40.688 CEST from /usr/local/bundle/gems/activestorage-6.0.0/lib/active_storage/engine.rb:111:in `block (2 levels) in <class:Engine>'
2019-10-24 13:03:40.688 CEST from /usr/local/bundle/gems/activesupport-6.0.0/lib/active_support/lazy_load_hooks.rb:72:in `class_eval'
2019-10-24 13:03:40.688 CEST from /usr/local/bundle/gems/activesupport-6.0.0/lib/active_support/lazy_load_hooks.rb:72:in `block in execute_hook'
...
2019-10-24 13:03:40.689 CEST from /usr/src/app/bin/rails:9:in `<top (required)>'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
2019-10-24 13:03:40.689 CEST from /usr/local/bundle/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
2019-10-24 13:03:40.689 CEST from /usr/src/app/bin/spring:15:in `require'
2019-10-24 13:03:40.689 CEST from /usr/src/app/bin/spring:15:in `<top (required)>'
2019-10-24 13:03:40.689 CEST from bin/rails:3:in `load'
2019-10-24 13:03:40.689 CEST from bin/rails:3:in `<main>'
2019-10-24 13:03:41.492 CESTContainer called exit(1).

Мой вопрос: почему я получаю эту ошибку? В процессе дырки все выглядит хорошо, и я шаг за шагом следовал инструкциям (единственное отличие - они используют MySQL, а здесь я использую Postgres).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...