Docker Postgres container is not starting for Rails Application

I am facing an issue on docker container. When I execute the docker-compose up to start the application the Postgres container is not starting.

Error which I get after docker-compose up

/usr/local/bundle/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `initialize': could not translate host name "db" to address: Name or service not known (PG::ConnectionBad)

Now it is frequently happing. I tried with few steps as add ports for db container i.e 5432:5432. I used to start-stop the specific db container so that the connection should get re-established but it is not working.

Application details:

Rails Version: 4.2.0 Ruby version: 2.2.0

docker-compose.yml

version: '3.7'

services:
  selenium:
    image: selenium/standalone-chrome-debug:3.141.59-krypton
    ports: ['4444:4444', '5900:5900']
    logging:
      driver: none
  redis:
    image: redis:3.0.0
  elastic:
    image: elasticsearch:1.5.2
  db:
    image: postgres:9.3.10
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
      - .:/home
  XYZ:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    stdin_open: true
    tty: true
    volumes:
      - XYZ-sync:/home:nocopy
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - elastic
      - selenium
    environment:
      - REDIS_URL=redis://redis:6379/0
      - ELASTICSEARCH_URL=elastic://elastic:9200/0
      - SELENIUM_HOST=selenium
      - SELENIUM_PORT=4444
      - TEST_APP_HOST=XYZ
      - TEST_PORT=3000

Any help will be appreciated.

Source: StackOverflow