Rails应用程序无法连接到在Docker上运行的Postgres

时间:2020-08-05 18:54:39

标签: ruby-on-rails postgresql docker docker-compose

我的docker-compose.yml文件具有以下内容:

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:

运行命令docker-compose up后,我知道数据库,用户和密码已正确创建,因为我可以使用docker exec -it df01156d5fbd psql -U myuser -W访问postgres控制台,并使用\l查看数据库。输出是

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)

但是在运行bundle exec rails s并输入localhost:3000时,出现以下错误 FATAL: password authentication failed for user "myuser"

我的database.yml文件如下

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

1 个答案:

答案 0 :(得分:0)

postgres服务器在端口5432的docker容器中运行,但是您的应用程序在主机上运行,​​并在端口5432的主机上搜索postgres服务器,但未找到它,因此失败。

尝试映射conatiner和主机的端口。

ports:
  - "5432:5432"