I am running rails + Redis + Postgres with docker and I have managed to finally get everything working the only thing i can’t figure out is the database. it seems that no matter what I put for host/username/password I always end up with connection refused
here is my setup:
docker-compose.yml
version: '3.4'
services:
app:
build:
context: .
dockerfile: Dockerfile
depends_on:
- database
- redis
ports:
- "3000:3000"
volumes:
- .:/app
- gem_cache:/usr/local/bundle/gems
env_file: .env
environment:
RAILS_ENV: development
database:
image: postgres:12.1
volumes:
- db_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
POSTGRES_USER: baopals
POSTGRES_PASSWORD: baopals
redis:
image: redis:5.0.7
volumes:
gem_cache:
db_data:
networks:
default:
external:
name: baopals-network
Dockerfile
FROM ruby:2.5.1-alpine
ENV BUNDLER_VERSION=1.16.1
RUN apk add --update --no-cache
binutils-gold
build-base
curl
file
g++
gcc
git
less
libstdc++
libffi-dev
libc-dev
linux-headers
libxml2-dev
libxslt-dev
libgcrypt-dev
make
netcat-openbsd
openssl
pkgconfig
postgresql-dev
python
tzdata
nodejs
RUN gem install bundler -v 1.16.1
WORKDIR /app
ADD vendor/gems/active_elastic_job-2.0.1 /app/vendor/gems/active_elastic_job-2.0.1
COPY Gemfile Gemfile.lock ./
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle check || bundle install
COPY . ./
ENTRYPOINT ["./entrypoints/docker-entrypoint.sh"]
.env
DB_NAME=baopals_development
DB_USER=baopals
DB_PASSWORD=baopals
DB_HOST=localhost
REDIS_HOST=redis
database.yml
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: baopals_development
username: baopals
password: baopals
host: localhost
port: 5432
and finally here is the error I end up with
app_1 | PG::ConnectionBad (could not connect to server: Connection refused
app_1 | Is the server running on host "localhost" (127.0.0.1) and accepting
app_1 | TCP/IP connections on port 5432?
app_1 | could not connect to server: Address not available
app_1 | Is the server running on host "localhost" (::1) and accepting
app_1 | TCP/IP connections on port 5432?
I am new with docker so im not sure if im just missing something obvious here
2
Answers
With Docker Compose, services (containers) automatically get a hostname identical to the service name. In your case the hostname for your Postgres service is
database
instead oflocalhost
.See https://docs.docker.com/compose/networking/
When you want to connect to PostgreSQL server via docker then you have to start docker container you made for postgresql like this way
sudo docker start mysql-55-container