![](/img/trans.png)
[英]Postgresql: No connection could be made because the target machine actively refused it
[英]dial tcp [::1]:5432: connectex: No connection could be made because the target machine actively refused it
我正在 Windows 上使用 Postgres 編寫 Go Web 應用程序。 我正在使用 pq 包連接到 Postgres。
這是我的數據庫連接函數
func ConnToDB() *sql.DB {
// load .env file
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
// Open the connection
db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
panic(err)
}
// check the connection
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
// return the connection
return db
}
我的環境變量
DATABASE_URL="postgres://postgres:pgpwd4me@localhost:5432/test?sslmode=disable"
但是當我運行這段代碼時,我得到
ERROR 2022/12/18 00:23:22 server.go:3228: http: panic serving [::1]:62981: dial tcp [::1]:5432: connectex: No connection could be made because the target machine actively refused it.
我整理了一個小代碼示例來幫助您找出問題。 首先,我使用以下命令通過 Docker 運行 Postgres:
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres
多虧了這個命令,每個試圖在端口5432
上聯系我的主機的連接都將自動轉發到我的容器的端口5432
。
源代碼與您分享的大致相同:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
conn, err := sql.Open("postgres", "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable")
if err != nil {
panic(err)
}
defer conn.Close()
if err := conn.Ping(); err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
我能夠成功聯系我的 Postgres 實例,所以這對你也應該有效。 讓我知道!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.