Home > Net >  ActiveRecord::ProtectedEnvironmentError after the second launch of docker-compose up
ActiveRecord::ProtectedEnvironmentError after the second launch of docker-compose up

Time:11-26

I am creating two docker containers for an application and a database. On the first launch of docker-compose up, the application is running. However, in the following attempts it appears:

Database 'time_distribution_production' already exists.
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your 'production' database.
If you are sure you want to continue, run the same command with the environment variable:
DISABLE_DATABASE_ENVIRONMENT_CHECK=1

Dockerfile

FROM ruby:3.1.2

ENV BUNDLER_VERSION=2.3.24

RUN apt update -qq && apt install -y libmsgpack-dev postgresql-client

RUN gem install bundler -v 2.3.24

RUN mkdir /time-distribution
WORKDIR /time-distribution

ENV RAILS_ENV production

COPY Gemfile .
COPY Gemfile.lock .

RUN bundle install

COPY . .

EXPOSE 3000

RUN chmod  x docker.sh
CMD ./docker.sh

docker.sh

#!/bin/bash
set -e

rm -f tmp/pids/server.pid

bundle exec rails db:setup
bundle exec rails db:migrate
bundle exec rails assets:precompile

bundle exec rails server -p 3000 -b '0.0.0.0'

docker-compose.production.yml

version: '3'

services:
  app:
    image: $IMAGE_NAME
    restart: always

  database:
    restart: always

database.yml for production database

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>


production:
  <<: *default
  database: <%= Rails.application.credentials.dig(:production, :postgres_name) %>
  username: <%= Rails.application.credentials.dig(:production, :postgres_username) %>
  password: <%= Rails.application.credentials.dig(:production, :postgres_password) %>
  host: database

I noticed that the error disappears when I reset volumes: docker compose down -volumes. I tried to restart the containers on the server. It didn't help. Please tell me how to solve the problem. Thank you very much in advance!

CodePudding user response:

This command in your docker.sh

bundle exec rails db:setup

will delete all data in the database. That is certainly not something you want to do in your production environment.

Instead, I suggest just trying to create a database with

bundle exec rails db:create

Which fails when the database already exists, but that can be ignored. In the next step, the migration will work no matter if the database is completely new or existed before:

bundle exec rails db:create
bundle exec rails db:migrate
bundle exec rails assets:precompile
  • Related