首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails服务器是否在主机"localhost“(127.0.0.1)上运行,并在端口5432上接受TCP/IP连接?

Rails服务器是否在主机"localhost“(127.0.0.1)上运行,并在端口5432上接受TCP/IP连接?
EN

Stack Overflow用户
提问于 2020-06-02 01:51:44
回答 1查看 1.9K关注 0票数 0

我正在构建一个rails应用程序,但在安装docker时遇到了问题。

构建工作正常,但当我尝试使用以下命令创建数据库时:

代码语言:javascript
运行
复制
docker-compose run web bundle exec rails db:create

它抛出这个错误:

代码语言:javascript
运行
复制
could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Address not available
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?

我已经尝试将主机从localhost重命名为db,它不起作用,我还尝试编辑我的etc/hosts。

docker-compose.yml

代码语言:javascript
运行
复制
version: '3'
services:
  localhost:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - localhost
    working_dir: /myapp

Dockerfile

代码语言:javascript
运行
复制
FROM ruby:2.6.2-alpine

RUN apk add --no-cache build-base postgresql-dev tzdata libxml2-dev libxslt-dev nodejs yarn

RUN mkdir /myapp
WORKDIR /myapp

COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
COPY package.json /myapp/package.json

RUN gem install bundler:2.1.2
RUN bundle install

COPY . /myapp

RUN yarn install --check-files

database.yml

代码语言:javascript
运行
复制
default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  username: postgres
  password:
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: myapp_development

/etc/hosts

代码语言:javascript
运行
复制
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
127.0.0.1 postgres

如何解决此问题?我不确定我错过了什么!

EN

回答 1

Stack Overflow用户

发布于 2020-06-02 02:02:12

在Docker中,每个“服务”都在自己的容器中运行。所以你应该将Rails应用程序和数据库放在不同的容器中。从概念上讲,每个服务都是一个不同的服务器。

您的错误(Is the server running on host "localhost" (127.0.0.1)..)表明您的Rails应用程序正在寻找同一台机器上的数据库引擎。该数据库在单独的服务器上运行。

在docker-compose文件中,每个服务都可以通过其名称寻址。因此,将Rails应用程序中的连接字符串或设置从localhost更改为db或其他什么。

编辑:我刚刚看到你把你的数据库服务器命名为localhost,这是自找麻烦。将其更改为db或其他什么?:)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62138016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档