每当我启动我的 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())
        }
    }

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

推荐答案

您需要等待,直到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

Database相关问答推荐

MongoDB事务,回调API方法

如何使用 SQL Server 中的round方法将浮点数转换为 int?

Sequel Pro / MAMP 在哪里存储本地数据库?

为什么引用 SQLite rowid 会导致外键不匹配?

为什么 COUNT() 只显示一行表格?

时间数据库设计,有一个转折(live vs draft rows)

有没有办法为 2 个具有不同包名称的应用程序提供 1 个 Firebase 数据库?

在 Oracle 中查找数据库的大小

按纬度/经度进行半径搜索

nodejs和数据库如何通信 ?

SQLAlchemy 和 django,准备好生产了吗?

查询表的外键关系

SQL Server 简单插入语句超时

SqlAlchemy 中的动态表创建和 ORM 映射

设计数据库时最重要的考虑因素是什么?

我们如何保存在 sqlite3 中创建的数据库

我什么时候应该考虑使用内存数据库,需要注意什么问题?

找不到类型或命名空间名称SQLConnection

为什么 DBMS 不支持 ASSERTION

计算邮政编码...和用户之间的距离.