首页 > 解决方案 > 无法在 Rails 和 Postgres Docker 容器之间建立连接

问题描述

我是 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,而且我不知道 Rails 容器为什么会尝试连接该地址。

标签: ruby-on-railspostgresqldockerdocker-compose

解决方案


正如大卫迷宫指出的那样:

需要将DATABASE_PORT设置为普通的PostgreSQL端口5432;端口:在容器间通信中被忽略(并且不必要)。


推荐阅读