WSL上的Rails设置:db:create结果为“无法连接到服务器错误”

问题描述

我正在尝试将Rails设置为可在WSL 2中使用。我已遵循this guide进行操作。执行命令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安装吗?

解决方法

我遵循相同的指南,并且遇到相同的问题。通过显式指定用于访问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设置了默认值。

,

如果您要在Windows环境中安装和使用postgres,而不是使用WSL?您应该在ubuntu(或您使用的任何其他发行版)上安装postgres。

我还使用WSL,并在ubuntu上安装了ruby,rails,postgres等,并且效果很好。