Hello - So I am a little new to Golang, but actively trying to learn how to create a webapp. So I ran across this library and I am trying to create a library that all my micro services would use - so this is my connection function:
package rdbms
// Connect connects to a RDBMS instance
func Connect(serviceName string) *pg.DB {
log.Log("Connecting " + serviceName + " to the RDBMS DataBase...")
db := pg.Connect(&pg.Options{
User: "postgres",
Password: "secret",
Database: "test_db",
})
log.Log("Sucessfully connected " + serviceName + " to RDBMS Database")
return db
}
Then in my services I import this package and do
var db = rdbms.Connect("user.service")
type User struct{
Email string
Firstname string
Lastname string
}
func Register(.....) {
user := &User{...........}
err := db.Insert(user)
}
I get a dial tcp 127.0.0.1:5432: getsockopt: connection refused
So I am using Docker-Compose to run my app:
rdbms:
image: postgres:10.2
container_name: "test_postgres_db"
restart: always
environment:
- POSTGRES_DB=test_db
- POSTGRES_PASSWORD=secret
ports:
- "5432:5432"
......
I am not sure what I am doing wrong here...any help or direction I would gladly appreciate!
Try to add Addr: ":5432" or localhost:5432 to pg.Options. Overall this does not look like a go-pg issue so try to verify that you can connect to Postgres server on localhost:5432 with psql client (or any other client of your choice).
@vmihailenco - so I tried adding both - and I still get "panic recovered: dial tcp 127.0.0.1:5432: getsockopt: connection refused"
I confirmed I am able to hit my DB with sql-migrate library and also I am able to docker exec ssh into my postgres docker container
@mdere try to run something like pgAdmin (or psql) on your computer (not in VM) and attempt a DB connection if you are running the app not in docker.
If you are running both the golang app and postgresql you most likely need to use 'rdbms' as the IP or 127.0.0.1 (You might have to look more into docker & postgres).
However if you are running the golang app on your computer and the docker is running PostgreSQL you will most likely need to use the 172.xx ip and might have to look into allowing your IP via ph_hba.conf AND set the 'listen_addresses' to *. (Test with pgAdmin or psql)
@yiiTT - thank you for directions - I will give this a try tonight and I will let you know.
@yiiTT you were right that I had to use my 172 ip !! - Ok now I have to figure out how to make my app smart enough to pull that correct IP that docker creates?
I'll close this for now - but I'll write up how to connect go-pg correctly with docker posgres later in this thread, for when people learning like me.
@mdere any chance you could do a write-up for a fix?
Most helpful comment
@mdere any chance you could do a write-up for a fix?