Golang连接PostgreSQL报connection refused错误求助
问题解决指南
一、WSL连接PostgreSQL失败(connection refused)
WSL2默认采用NAT网络,localhost指向WSL内部而非Windows主机,直接用localhost无法连接Windows上的PostgreSQL,可通过以下两种方式解决:
- 修改PostgreSQL监听配置:
- 打开Windows上PostgreSQL的
postgresql.conf,将listen_addresses改为*(允许所有IP访问)。 - 打开
pg_hba.conf,添加一行host all all 0.0.0.0/0 md5(允许所有IP通过密码登录),随后重启PostgreSQL服务。
- 打开Windows上PostgreSQL的
- WSL中使用Windows主机IP连接:
在WSL终端执行cat /etc/resolv.conf,找到nameserver后的IP(即Windows网关IP),将连接串里的host=localhost替换为该IP。
二、PowerShell中程序能连但Postman调用接口失败
- 检查服务绑定地址:确保你的HTTP服务绑定了
0.0.0.0而非仅127.0.0.1,否则可能因IP限制导致Postman无法访问。 - 排查接口逻辑问题:当前代码中
UpdateAccount、GetAccountByID等方法仅返回nil,无实际业务逻辑;同时代码存在SQL语法错误(下文会详述),这些都会导致接口无法正常响应Postman请求。
三、Docker部署后无法连接数据库
- PostgreSQL在Windows主机上:Docker容器内的
localhost指向容器自身,需将连接串的host改为host.docker.internal(Windows Docker Desktop支持该域名,指向宿主机)。 - PostgreSQL也在Docker容器中:
- 使用Docker Compose时,将Go服务与PostgreSQL放入同一网络,连接串的
host设为PostgreSQL的服务名称(如postgres)。 - 手动启动容器时,确保两者处于同一网络,用PostgreSQL容器的IP或名称作为
host值。
- 使用Docker Compose时,将Go服务与PostgreSQL放入同一网络,连接串的
四、代码中的关键错误修复
当前代码存在多处语法与逻辑错误,会直接导致数据库操作失败:
- SQL字段不匹配:
- 表结构字段为
last,但CreateAccount插入语句使用last_name,需改为last。 - 表结构字段为
create_at,插入语句使用created_at,需改为create_at。
- 表结构字段为
- SQL语法错误:
CreateAccount的SQL语句中values ($1, 2$, $3)存在笔误,2$需改为$2。 - API方法误用:
插入操作无需使用db.Query(用于查询返回结果),改用db.Exec更合适,避免占用结果集资源。
修复后的核心代码示例:
// 补充Account结构体定义(原代码缺失) type Account struct { ID int `json:"id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` CreatedAt time.Time `json:"created_at"` } func (s *PostgresStore) createAccountTable() error { query := `create table if not exists account ( id serial primary key, first_name varchar(50), last varchar(50), create_at timestamp )` _, err := s.db.Exec(query) return err } func (s *PostgresStore) CreateAccount(acc *Account) error { query := `insert into account (first_name, last, create_at) values ($1, $2, $3)` _, err := s.db.Exec( query, acc.FirstName, acc.LastName, acc.CreatedAt) if err != nil { return err } return nil }
内容的提问来源于stack exchange,提问作者OMojJegoMosc
相关产品推荐
相关产品推荐

