簡體   English   中英

無法初始化數據庫,出現錯誤無法連接到`host=db user=database=`:撥號錯誤(dial tcp xxxx: connect: connection refused)

[英]failed to initialize database, got error failed to connect to `host=db user= database=`: dial error (dial tcp xxxx: connect: connection refused)

每當我啟動我的 docker 容器服務時,我都會收到failed to initialize錯誤。

version: '3'

services:
  app:
    container_name: api
    build:
      context: .
      dockerfile: local.Dockerfile
    ports:
      - "9090:9090"
      - "40000:40000"
    security_opt:
      - "seccomp:unconfined"
    cap_add:
      - SYS_PTRACE
    restart: on-failure
    environment:
      PORT: 9090
      DB_CONN: "postgres://admin:pass@db:5432/test?sslmode=disable"
    volumes:
      - .:/app
    depends_on:
      - db
    links:
      - db

  db:
    image: postgres
    container_name: db
    ports:
      - "5432:5432"
    environment:         
      POSTGRES_USER: "admin"
      POSTGRES_PASSWORD: "pass"
      POSTGRES_DB: "test"
      TZ: "UTC"
      PGTZ: "UTC"
    volumes:
      - ./tmp:/var/lib/postgresql/data

我正在使用air進行實時重新加載,請找到air.toml文件

root="."
tmp_dir="tmp"

[build]
cmd="go build -gcflags=\"all=-N -l\" -o ./bin/main ."
bin="/app/bin"
full_bin="/app/bin/main"
log="air_errors.log"
include_ext=["go", "yaml"]
exclude_dir=["tmp"]
delay=1000

[log]
time=true


[misc]
clean_on_exit=true




func main() {
    Instance, err = gorm.Open(postgres.Open(conn), &gorm.Config{
            Logger: logger.New(
                log.New(os.Stdout, "", log.LstdFlags), logger.Config{
                    LogLevel: logger.Info,
                    Colorful: true,
                }),
        })
        if err != nil {
            panic("Cannot connect to DB" + err.Error())
        }
    }

如果您再次保存代碼並實時重新加載應用程序,則會建立連接

您需要等到postgres數據庫初始化完成。

看看https://docs.docker.com/compose/compose-file/compose-file-v3/#healthcheck

db服務添加健康healthcheck

healthcheck:
    test: ["CMD-SHELL", "pg_isready"]
    interval: 10s
    timeout: 5s
    retries: 5

並更改depend_on如下

depends_on:
  db:
    condition: service_healthy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM