Failed to connect to database from rails console on docker

I have a rails project setup on Digitalocean

with Dockers

. This is my file docker-compose.prod.yml

.

version: "2"

volumes:
 db-data:
   external: false

services:
 db:
  image: postgres
  env_file: .env.production
 volumes:
   - db-data:/var/lib/postgresql/data

app:
 build: .
 env_file: .env
 environment:
   RAILS_ENV: production
 ports:
   - "3000:3000"
 depends_on:
   - db

      

and this is my database.yml

file

default: &default
 adapter: postgresql
 encoding: unicode
 host: db
 username: <%= ENV["POSTGRES_USER"] %>
 password: <%= ENV["POSTGRES_PASSWORD"] %>
 # For details on connection pooling, see rails configuration guide
 # http://guides.rubyonrails.org/configuring.html#database-pooling
 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
 <<: *default
 database:  project_development

test:
 <<: *default
 database: project_test

production:
 <<: *default
 host: <%= ENV["POSTGRES_HOST"] %>
 database: project_production

      

I have created two docker

images. One for app

and one for postgres/db

.

My application

works great in production. I can create and delete posts from my page web

on creation.

But, when i try to access rails console from production database

from docker bash with the following commands:

docker run -i -t project_app:latest bash 

      

to access the console:

RAILS_ENV=production rails c

      

Internally Rails Console

, whenever I try to access any data model

or try to execute any request ( i.e Model.first

etc.), I cannot access the database postgres

. It shows me the following error:

PG::ConnectionBad: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

      

I tried to find many possible solutions to solve this problem, but I was unable to resolve this issue.

Please help me! thanks in advance

+3


source to share


2 answers


After trying a lot I found a solution. I used a command docker run -i -t project_app:latest bash

to access container

and run a command rails console

that was wrong.

The correct command to access the terminal container

is



 docker exec -it project_app /bin/bash

      

After accessing, terminal

I was able to successfully run query

ie User.first

inside rails console

.

0


source


Here: docker run -i -t project_app:latest bash

you do not provide env vars that your application should use as credentials.

So use your docker-compose which already installs the env vars here:

env_file: .env

      



So, follow these steps:

docker run --env-file .env -i -t project_app:latest bash

      

0


source







All Articles