我正在构建Rails应用,安装docker时遇到问题。
构建工作正常,但是当我尝试使用此命令创建数据库时:
docker-compose run web bundle exec rails db:create
它抛出此错误:
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
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
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
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
# 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
如何解决此问题?我不确定我缺少什么!
答案 0 :(得分:1)
在Docker中,每个“服务”都在其自己的容器中运行。因此,您将把Rails应用程序和数据库放在不同的容器中。从概念上讲,每个服务都是一台不同的服务器。
您的错误(Is the server running on host "localhost" (127.0.0.1)..
)表明您的Rails应用程序正在同一台机器上寻找数据库引擎。该数据库正在单独的服务器上运行。
在docker-compose文件中,每个服务均可通过其名称进行寻址。因此,将Rails应用程序中的连接字符串或设置从localhost
更改为db
。
编辑:我刚才看到您将数据库服务器命名为localhost
,这很麻烦。将其更改为db
还是其他? :)