A
A
arruah2018-10-30 13:59:25
PostgreSQL
arruah, 2018-10-30 13:59:25

How to link two containers using docker-compose?

There are two containers RoR and Postgres, I'm trying to set up a network between them so that they can see each other by name.
docker-compose.yml

version: '3.2'
services:
  postgres:  
    image: postgres
    volumes:
      - config-volume:/var/lib/postgresql/data/
  rails:
    build:
       context: backend/
       dockerfile: Dockerfile
    links:
      - "postgres:db"
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/backend
    ports:
      - "3000:3000"
    depends_on: 
      - 'postgres'
  
  angular:
    build:
      context: frontend/
      dockerfile: Dockerfile
    command: ng serve --host 0.0.0.0
    volumes:
      - .:/frontend
    ports:
      - "4200:4200"
volumes:
  config-volume:

Dockerfile for backend (RoR)
FROM ruby:2.5.1

RUN apt-get update && apt-get install -qq -y --no-install-recommends \
    build-essential \
    nodejs \
    libpq-dev \
 && rm -rf /var/lib/apt/lists/*

RUN mkdir /rails_app
WORKDIR /rails_app

COPY . .

# RUN echo "ruby '2.5.0'\n source 'https://rubygems.org'\n gem 'rails', '~> 5.1.0'\n" > Gemfile
RUN bundle install
RUN rake db:migrate:reset

# RUN rails new temp_app
# RUN rm -rf temp_app

# CMD ['bundle', 'exec', 'rails', 'server']

config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  host: postgres
  # For details on connection pooling, see Rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

When I do docker-compose build and docker-compose up I get an error:
rake aborted!
PG::ConnectionBad: could not translate host name "postgres" to address: Name or service not known
/usr/local/bundle/gems/pg-1.0.0/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-1.0.0/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-1.0.0/lib/pg.rb:56:in `connect'

From which I conclude that the link did not work.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Q
qlkvg, 2018-10-30
@arruah

in the output of docker container ps, what is in the NAME field of the container with the base?
try like this

postgres:  
    image: postgres
    container_name: postgres
    volumes:
      - config-volume:/var/lib/postgresql/data/

links not needed[2]

D
Dmitry, 2018-10-30
@q2digger

in docker-compose the container is named "postgres" , not "postgresql"..

Q
qq1, 2018-10-30
@qq1

Compare host in database.yml and database service name in docker-compose.yml
PS
links are now considered deprecated and are not actually needed

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question