php editor Xiaoxin recently encountered a problem, which is a connection problem when using the Gorm application on Mac to connect to PostgreSQL in a docker container. The specific performance is that the DSN is ignored. DSN is the abbreviation of data source name and is used to specify database connection information. This problem annoys me to no end because not being able to connect to the database will cause the application to not run properly. Next, I will share the problems I encountered and the solutions, hoping to help everyone.
I try to create a simple go rest api. I am using gorm library for database processing but it cannot connect to the database in the container. I think this might be an issue with docker on the apple chip, but not sure. I have another project that uses basically the same setup but has absolutely no issues connecting to the database.
Basically, the connection parameters seem to change completely at runtime, ignoring the dsn string
This is docker-compose.yml
:
version: '3' services: db: image: 'postgres:latest' container_name: bazos-watcher-db ports: - '5420:5432' volumes: - dbdata:/var/lib/postgresql/data - ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql env_file: - 'docker.env' restart: always volumes: dbdata:
This is the part that makes the database connection:
dsn := "bazos:kokos@tcp(localhost:5420)/bazos?charset=utf8mb4&parsetime=true&loc=local" dbopen, err := gorm.open(postgres.open(dsn), &gorm.config{})
dsn parameter matches the parameters configured in docker.env
. pgadmin has no problem establishing the connection.
This is the error I'm getting, for some reason the connection parameters seem to have changed completely:
[error] failed to initialize database, got error failed to connect to `host=/private/tmp user=tassilo database=`: dial error (dial unix /private/tmp/.s.PGSQL.5432: connect: no such file or directory) 2023/03/15 17:20:59 failed to connect to `host=/private/tmp user=tassilo database=`: dial error (dial unix /private/tmp/.s.PGSQL.5432: connect: no such file or directory) exit status 1
I tried changing the last part of the dsn string and deleting and recreating the container, but still no success.
I naively assumed that the dsn string was in the same format as mysql. Instead, it should look like this:
dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
The above is the detailed content of Gorm application cannot connect to PostgreSQL in docker container on Mac, ignoring DSN. For more information, please follow other related articles on the PHP Chinese website!