gpt4 book ai didi

ruby-on-rails - 无法在Rails和Postgres Docker容器之间建立连接

转载 作者:行者123 更新时间:2023-12-02 19:44:47 30 4
gpt4 key购买 nike

我是Docker的新手,并尝试使用docker-compose来对Rails容器和Postgres容器进行docker化,并同时进行构建和启动,但是当我尝试转到localhost:3009以查看“是的,您在Rails”页面上时,我在Rails日志中得到以下错误:

Started GET "/" for 172.27.0.1 at 2020-10-05 12:40:18 +0000
backend_1 | Cannot render console from 172.27.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
backend_1 |
backend_1 | PG::ConnectionBad (could not connect to server: Connection refused
backend_1 | Is the server running on host "postgres" (172.27.0.2) and accepting
backend_1 | TCP/IP connections on port 5439?
backend_1 | ):
这是我的docker-compose.yml:
version: '3'

volumes:
db_data:
driver: local
app_data:
driver: local

services:
# database container
postgres:
image: postgres
volumes:
- app_data:/var/lib/postgresql/data
ports:
- 5439:5432
environment:
POSTGRES_DB: db_name
POSTGRES_USER: user
POSTGRES_PASSWORD: xxxxxx
command: ["postgres", "-c", "log_statement=all"]
restart: always

app:
build: ./server
volumes:
- ./server:/code
ports:
- "3009:3000"
depends_on:
- postgres
environment:
RAILS_ENV: development
DATABASE_HOST: postgres
DATABASE_PORT: 5439
DATABASE_NAME: db_name
DATABASE_USERNAME: user
DATABASE_PASSWORD: xxxxxx
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
这是Dockerfile:
FROM ruby:2.7.1

WORKDIR /app

COPY . /app

# Install NodeJS and Yarn.
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN apt-get update && apt-get install -y yarn

RUN yarn install --check-files

RUN bundle install

CMD ["rails", "server", "-b", "0.0.0.0"]
这是我的database.yml
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
host: <%= ENV['DATABASE_HOST'] %>
port: <%= ENV['DATABASE_PORT'] %>
database: <%= ENV['DATABASE_NAME'] %>
username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>

development:
<<: *default

test:
<<: *default
我可以使用172.27.0.1:5439访问DBeaver中的pg数据库,但是不能使用172.27.0.2:5439访问pg数据库,而且我不知道Rails容器为何尝试在该地址上进行连接。

最佳答案

正如David Maze指出的那样:

You need to set DATABASE_PORT to the ordinary PostgreSQL port 5432; ports: are ignored (and unnecessary) for inter-container communications.

关于ruby-on-rails - 无法在Rails和Postgres Docker容器之间建立连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64209788/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com