[英]Cannot establish connection between Rails and Postgres Docker containers
I am new to Docker and try to dockerize a Rails container and a Postgres container with docker-compose and both build and start but when I try to go to localhost:3009 to see the "Yay, you're on Rails" page, I get this error in the Rails logs:我是 Docker 的新手,并尝试使用 docker-compose 对 Rails 容器和 Postgres 容器进行 docker-compose 构建和启动,但是当我尝试转到 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 | ):
This is my docker-compose.yml:这是我的 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'"
And this is the Dockerfile:这是 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"]
This is my database.yml这是我的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
I can access the pg database in DBeaver with 172.27.0.1:5439, but not with 172.27.0.2:5439 and I have no clue why the Rails container tries to connect on that address.我可以使用 172.27.0.1:5439 访问 DBeaver 中的 pg 数据库,但不能使用 172.27.0.2:5439,我不知道为什么 Rails 容器尝试连接到该地址。
As David Maze pointed out:正如大卫·梅兹指出的那样:
You need to set DATABASE_PORT to the ordinary PostgreSQL port 5432;需要将DATABASE_PORT设置为普通PostgreSQL端口5432; ports: are ignored (and unnecessary) for inter-container communications.端口:对于容器间通信被忽略(和不必要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.