我正在尝试使用docker-compose运行Rails / Postgres应用,但是在不设置POSTGRES_HOST_AUTH_METHOD="trust"
的情况下创建数据库时遇到了麻烦。以下docker-compose.yml在“信任”下似乎可以正常工作:
version: '3'
services:
db:
image: postgres:alpine
env_file: .env
environment:
POSTGRES_HOST_AUTH_METHOD: "trust"
volumes:
- ./tmp/db:/var/lib/postgresql/data
web:
build:
context: .
dockerfile: Dockerfile
command: bundle exec rails server -b '0.0.0.0' -p 3000
env_file: .env
ports:
- "3000:3000"
volumes:
- .:/app
- node_modules:/app/node_modules/
depends_on:
- db
volumes:
node_modules:
为了使此工作不带“信任”,我理解在初始化Postgres图像以设置默认用户密码时,必须定义环境变量POSTGRES_PASSWORD
。因此,我们使用以下.env文件,已由docker-compose引用:
POSTGRES_URL=db
POSTGRES_PASSWORD=foobar
并更改config / database.yml以使用以下默认连接配置:
...
default: &default
adapter: postgresql
encoding: unicode
host: <%= ENV['POSTGRES_URL'] %>
# If POSTGRES_PASSWORD is set in the environment then use the default user
# and that password to connect. If none is set, then assume that the creds
# are elsewhere (e.g. included in POSTGRES_URL on Heroku)
<% if ENV['POSTGRES_PASSWORD'].present? %>
username: postgres
password: <%= ENV['POSTGRES_PASSWORD'] %>
<% end %>
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
...
然后我在控制台中执行以下操作:
$ docker-compose build
db uses an image, skipping
Building web
...
$ docker-compose run web echo container started successfully
Starting rails-dockerized_db_1 ... done
container started successfully
$ docker-compose run web bundle exec rails db:create
Starting rails-dockerized_db_1 ... done
FATAL: password authentication failed for user "postgres"
Couldn't create 'rails_dockerized_development' database. Please check your configuration.
rails aborted!
ActiveRecord::NoDatabaseError: FATAL: password authentication failed for user "postgres"
...
据我所知,此配置应该正确,但是我显然忽略了某些内容。为什么我看到此身份验证失败?
在您的.env文件中添加POSTGRES_USER=postgres
PostgreSQL需要POSTGRES_USER
https://github.com/x1wins/tutorial-rails-rest-api/blob/master/docker-compose.yml