Golang连接到Postgres时的Docker错误

huangapple go评论71阅读模式
英文:

Golang docker error while connecting to postgres

问题

我正在尝试使用docker-compose.yml文件将我的Golang REST API进行Docker化。

假设我当前没有任何Docker镜像。我只需运行以下命令:

docker-compose up -d

它会自动创建两个Docker镜像,一个是数据库的镜像,另一个是代码的镜像。

但是,当我运行以下命令查看日志时:

docker-compose logs

我得到以下日志:

Attaching to posty-api_api_1, postgres
postgres    | 
postgres    | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres    |
postgres    | 2021-06-14 07:37:46.437 UTC [1] LOG:  starting PostgreSQL 13.3 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit
postgres    | 2021-06-14 07:37:46.438 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres    | 2021-06-14 07:37:46.438 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres    | 2021-06-14 07:37:46.481 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres    | 2021-06-14 07:37:46.607 UTC [22] LOG:  database system was shut down at 2021-06-14 07:33:40 UTC
postgres    | 2021-06-14 07:37:46.696 UTC [1] LOG:  database system is ready to accept connections
api_1       | main.go start
api_1       | database.go START
api_1       |
api_1       | 2021/06/14 07:37:45 /app/database/database.go:23
api_1       | [error] failed to initialize database, got error failed to connect to `host=postgres user=postgres database=postgres`: dial error (dial tcp 172.22.0.2:5432: connect: connection refused)
api_1       | panic: failed to connect database
api_1       |
api_1       | goroutine 1 [running]:
api_1       | github.com/usman-174/database.ConnectDataBase(0xc0001ae2f0)
api_1       |   /app/database/database.go:26 +0x49a
api_1       | github.com/usman-174/app.Router(0xa7c120)
api_1       |   /app/app/app.go:10 +0x26
api_1       | main.main()
api_1       |   /app/main.go:16 +0x9b

我无法连接到数据库,即使我提供了正确的环境变量。

这是我的.env文件内容:

DSN=host=postgres user=postgres password=postgres dbname=postgres port=5432 sslmode=disable
CLIENT_URL=https://clever-montalcini-cedd07.netlify.app/
PORT=:8080

这是我的Dockerfile内容:

FROM golang:1.16.5-alpine3.13 AS builder
WORKDIR /app
COPY . .
RUN go build -o main main.go

# Run stage
FROM alpine:3.13
WORKDIR /app
COPY --from=builder /app/main .
COPY .env .
EXPOSE 8080

这是我的docker-compose.yml文件内容:

# Specify the version for docker-compose.yml
version: "3.8"

# add the serivces needed (postgres,go)
services:
  postgres:
    container_name: postgres
    image: postgres:13-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: auth
      # Optional: Give a name to the database, otherwise
      # use the default value POSTGRES_USER as a database name (user in this case.)
      POSTGRES_DB: auth
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data

  api:
    build:
      context: .
      dockerfile: Dockerfile
    command: ["./wait-for-it.sh", "postgres:5432", "--", "/app/main" ]
    ports:
      - "8080:8080"
    depends_on:
      - postgres
    command: [ "/app/main" ]

这是我连接到数据库的方式:

func ConnectDataBase() *gorm.DB {
    fmt.Println("database.go START")
    err := godotenv.Load()

    if err != nil {
        log.Fatal("Error loading .env file")
    }
    dsn := os.Getenv("DSN")
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        panic("failed to connect database")
    }
    db.AutoMigrate(&models.User{})
    db.AutoMigrate(&models.Post{})
    db.AutoMigrate(&models.Like{})
    fmt.Println("database.go STOP")

    return db
}

以上是你要翻译的内容。

英文:

I am Trying to dockerize my golang rest api with docker-compose.yml file.

Suppose currently I dont have any docker images. I just

> run docker-compose up -d

It automatically creates 2 docker images 1 of database and 1 of the code.

But when I see the log by running command

> docker-compose logs

I get these logs

Attaching to posty-api_api_1, postgres
postgres    | 
postgres    | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres    |
postgres    | 2021-06-14 07:37:46.437 UTC [1] LOG:  starting PostgreSQL 13.3 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit
postgres    | 2021-06-14 07:37:46.438 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres    | 2021-06-14 07:37:46.438 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres    | 2021-06-14 07:37:46.481 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres    | 2021-06-14 07:37:46.607 UTC [22] LOG:  database system was shut down at 2021-06-14 07:33:40 UTC
postgres    | 2021-06-14 07:37:46.696 UTC [1] LOG:  database system is ready to accept connections
api_1       | main.go start
api_1       | database.go START
api_1       |
api_1       | 2021/06/14 07:37:45 /app/database/database.go:23
api_1       | [error] failed to initialize database, got error failed to connect to `host=postgres user=postgres database=postgres`: dial error (dial tcp 172.22.0.2:5432: connect: connection refused)
api_1       | panic: failed to connect database
api_1       |
api_1       | goroutine 1 [running]:
api_1       | github.com/usman-174/database.ConnectDataBase(0xc0001ae2f0)
api_1       |   /app/database/database.go:26 +0x49a
api_1       | github.com/usman-174/app.Router(0xa7c120)
api_1       |   /app/app/app.go:10 +0x26
api_1       | main.main()
api_1       |   /app/main.go:16 +0x9b

I cant connect with the data base. Even I provide correct env variables.

This is my .env file:

DSN=host=postgres user=postgres password=postgres dbname=postgres port=5432 sslmode=disable
CLIENT_URL=https://clever-montalcini-cedd07.netlify.app/
PORT=:8080

This is my dockerfile:

FROM golang:1.16.5-alpine3.13 AS builder
WORKDIR /app
COPY . .
RUN go build -o main main.go

# Run stage
FROM alpine:3.13
WORKDIR /app
COPY --from=builder /app/main .
COPY .env .
EXPOSE 8080

This is my docker-compose.yml file:

# Specify the version for docker-compose.yml
version: "3.8"

# add the serivces needed (postgres,go)
services:
  postgres:
    container_name: postgres
    image: postgres:13-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: auth
      # Optional: Give a name to the database, otherwise
      # use the default value POSTGRES_USER as a database name (user in this case.)
      POSTGRES_DB: auth
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data

  api:
    build:
      context: .
      dockerfile: Dockerfile
    command: ["./wait-for-it.sh", "postgres:5432", "--", "/app/main" ]
    ports:
      - "8080:8080"
    depends_on:
      - postgres
    command: [ "/app/main" ]

And this is how I connect to my database:

func ConnectDataBase() *gorm.DB {
fmt.Println("database.go START")
err := godotenv.Load()

if err != nil {
	log.Fatal("Error loading .env file")
}
dsn := os.Getenv("DSN")
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

if err != nil {
	panic("failed to connect database")
}
db.AutoMigrate(&models.User{})
db.AutoMigrate(&models.Post{})
db.AutoMigrate(&models.Like{})
fmt.Println("database.go STOP")

return db
}

答案1

得分: 4

似乎DSN中的数据库名称不正确。

在你的docker-compose.yml文件中是这样的:

POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: auth
...

而在你的.env文件中是这样的:

DSN=host=postgres user=postgres password=postgres dbname=postgres ...

尝试在.env文件中使用dbname=auth而不是dbname=postgres

英文:

Seems like the database name on the DSN is incorrect.

On your docker-compose.yml it's:

POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: auth
...

meanwhile, on your .env it's:

DSN=host=postgres user=postgres password=postgres dbname=postgres ...

try to use dbname=auth instead of dbname=postgres on the .env file

huangapple
  • 本文由 发表于 2021年6月14日 16:24:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/67967031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定