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

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

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

问题

每当我启动我的Docker容器服务时,都会出现“无法初始化”的错误。

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())
    }
}

如果您再次保存代码并使用air进行实时重载应用程序,则连接将建立。

英文:

I am getting the failed to initialize error whenever I start up my docker container service.

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

I am using air for live reload, please find the air.toml file

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())
    	}
    }

The connection gets established if you save the code again and air live reload the appliation

答案1

得分: 1

你需要等待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
英文:

You need to wait until the postgres database has been initialized.

Have a look at https://docs.docker.com/compose/compose-file/compose-file-v3/#healthcheck

Add a healthcheck for db service

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

And change depend_on as below

depends_on:
  db:
    condition: service_healthy

huangapple
  • 本文由 发表于 2022年12月16日 22:23:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/74825752.html
匿名

发表评论

匿名网友

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

确定