每當啟動 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
以上是初始化資料庫失敗,出現錯誤無法連線到`host=db user=database=`:撥號錯誤(撥號tcp xxxx:連線:連線被拒絕)的詳細內容。更多資訊請關注PHP中文網其他相關文章!