简体   繁体   English

Rails 应用程序无法连接到在 docker 上运行的 postgres

[英]Rails application cannot connect to postgres running on docker

My docker-compose.yml file has the following:我的 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:

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 .运行命令docker-compose up我知道数据库、用户和密码已正确创建,因为我可以使用docker exec -it df01156d5fbd psql -U myuser -W访问 postgres 控制台并使用\l查看数据库。 The output for this was output 是

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"但是,当运行bundle exec rails s并输入localhost:3000我有以下错误FATAL: password authentication failed for user "myuser"

My database.yml file is the following我的 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

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. postgres 服务器在您的 docker 容器内的端口 5432 上运行,但您的应用程序正在主机上运行,并在端口 5432 上搜索主机上的 postgres 服务器,但没有找到它因此失败。

Try mapping the ports of the conatiner and the host machine.尝试映射容器和主机的端口。

ports:
  - "5432:5432"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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