I tried creating a simple go rest api. I use the Gorm library for DB handling, but it fails connecting to the DB in the container. I feel like this could be an issue of Docker on Apple silicon, but not sure. I have another project, which uses basically the same setup, but there’s no problem with DB connections at all.
Basically the connection parameters seem to change completely at runtime ignoring the DSN string
Here’s the 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:
Here’s the part that does the DB connection:
dsn := "bazos:kokos@tcp(localhost:5420)/bazos?charset=utf8mb4&parseTime=True&loc=Local"
dbOpen, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
The DSN parameters match those configured in docker.env
. pgAdmin has no problem making a connection.
Here’s the error I get, the connection parameters seem change completely for some reason:
[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 have tried changing the last part of the DSN string and deleting and recreating the container but still no success.
3
Answers
I naively assumed the format for DSN string is the same as for MySQL. Instead it should look like this:
I believe your problem is with
@tcp(localhost:5420)
– in Docker, your database service is specified asdb
and so your dsn should be@tcp(db)
. You may also need to specify the local driver in your docker compose:docker-compose down db
docker-compose up db -d
I hope it would work.