Docker - Rails app cannot connect to linked Postgr

2019-02-24 05:47发布

问题:

I've been following this guide of how to set up a Rails Development Environment using Docker: Setting Up A Rails Development Environment Using Docker.

I've hit a few snags along the way, but I've managed to get through most of them up until the step of running Rails migration. Running the command docker-compose run web rake db:migrate yields the following result:

rake aborted!
PG::ConnectionBad: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

docker-compose.yml:

version: '2'
services:
  db:
    image: postgres
    volumes:
      - ./pgdata:/pgdata
    environment:
      POSTGRES_DB: myapp_development
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD:
      PGDATA: /pgdata
  web:
    build: .
    command: bundle exec rails server --port 5000 --binding 0.0.0.0
    volumes_from:
      - container:myapp-web-sync:rw
      - container:myapp-bundle-sync:rw
    volumes:
      - ./keys:/root/.ssh/
    ports:
      - "5000:5000"
    environment:
      REDIS_URL: redis://redis:6379
      GEM_HOME: /bundle
    links:
      - db
      - redis
volumes:
  myapp-web-sync:
    external: true
  myapp-bundle-sync:
    external: true

回答1:

You try to connect to localhost:5432 in other words you try to connect to the web container, but your point is db. Just specify Database host in your application like db