简体   繁体   中英

Rails application cannot connect to postgres running on docker

My docker-compose.yml file has the following:

version: '3'
services:
  postgresql:
    image: postgres:11.3
    environment:
      - POSTGRES_USER=myuser
      - POSTGRES_PASSWORD=mypassword
    ports:
      - 5432
    volumes:
    - postgresql_data:/var/lib/postgresql/data
  
volumes:
  postgresql_data:

After running the command docker-compose up I know the database, user and password were created correctly since I can access the postgres console using docker exec -it df01156d5fbd psql -U myuser -W and see the databases using \l . The output for this was

myuser=# \l
                                            List of databases
      Name      |     Owner      | Encoding |  Collate   |   Ctype    |         Access privileges         
----------------+----------------+----------+------------+------------+-----------------------------------
 myuser         | myuser         | UTF8     | en_US.utf8 | en_US.utf8 | 
 postgres       | myuser         | UTF8     | en_US.utf8 | en_US.utf8 | 
 template0      | myuser         | UTF8     | en_US.utf8 | en_US.utf8 | =c/myuser                        +
                |                |          |            |            | myuser=CTc/myuser
 template1      | myuser         | UTF8     | en_US.utf8 | en_US.utf8 | =c/myuser                        +
                |                |          |            |            | myuser=CTc/myuser
(4 rows)

However when runing bundle exec rails s and entering localhost:3000 I have the following error FATAL: password authentication failed for user "myuser"

My database.yml file is the following

development: &default
  adapter: postgresql
  database: <%= ENV["DB_NAME] || 'myuser' %>
  encoding: utf8
  host: <%= ENV["DB_HOST"] || "127.0.0.1" %>
  port: <%= ENV["DB_PORT"] || 5432 %>
  username: <%= ENV["DB_USER"] || 'myuser' %>
  password: <%= ENV["DB_PASSWORD"] || 'mypassword' %>
  min_messages: warning
  pool: <%= Integer(ENV.fetch("DB_POOL", 5)) %>
  reaping_frequency: <%= Integer(ENV.fetch("DB_REAPING_FREQUENCY", 10)) %>
  timeout: 5000

The postgres server is running inside your docker container on port 5432, but your application is running on the host machine and searches for postgres server on host at port 5432 and does not finds it hence fails.

Try mapping the ports of the conatiner and the host machine.

ports:
  - "5432:5432"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM