首页 > 解决方案 > WSL 上的 Rails 设置:db:create 导致“无法连接到服务器错误”

问题描述

我正在尝试将 Rails 设置为在 WSL 2 中工作。我已按照本指南进行操作。在执行命令时,rails db:create我收到以下错误:

could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
Couldn't create 'myapp_development' database. Please check your configuration.
rails aborted!
ActiveRecord::NoDatabaseError: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
/home/ke/rails/myapp/bin/rails:9:in `<top (required)>'
/home/ke/rails/myapp/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'

Caused by:
PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
/home/ke/rails/myapp/bin/rails:9:in `<top (required)>'
/home/ke/rails/myapp/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:create
(See full trace by running task with --trace)

按照说明,我使用 Enterprise DB 的交互式安装程序安装了 postgresql。WSL 安装是否有某种方式无法在 Windows 上看到 postgres 安装?

标签: ruby-on-railspostgresqlwindows-subsystem-for-linux

解决方案


我遵循相同的指南并遇到了同样的问题。通过显式指定访问 postgres 数据库的主机、用户名和密码来修复它,就像在 database.yml 中一样:

default: &default
  adapter: postgresql
  encoding: unicode
  host: 127.0.0.1 # or localhost
  username: postgres # or your username
  password: ENV['POSTGRESQL_PASSWORD'] # or your password
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

问题是 WSL (ubuntu) 试图通过不存在的 Unix 套接字连接到 windows 上的 postgres。就像--host在运行时使用选项一样psql --host=127.0.0.1 database_name,我们在这里为 rails 设置了默认值。


推荐阅读