简体   繁体   中英

How does golang app talk to postgres using docker in aws servers?

I have a docker instance like this

docker run --name my-db-name -e POSTGRES_PASSWORD=mysecretpassword -d postgres:latest

running in a server

And I have my golang app wrapped by docker running in the same server

func main() {
    db, _ := sql.Open("postgres", "postgres://postgres:@192.168.99.100:5432/postgres?sslmode=disable")

    http.HandleFunc("/test", handler)
    http.ListenAndServe(":8080", nil)
}

The above is not working because the ip is not correct.

Since I am using mac, I need to use docker machine ip to connect to the docker postgres db, but in aws I don't

What is a good way to configure this?

Are you asking how to configure different environments for your local development and for AWS?

If so, you could use environment variables like this:

env := os.Getenv("GO_ENV")
dbIP := "DOCKER_MACHINE_IP"
if env == "production" {
    dbIP = "AWS_POSTGRES_IP"
}

And simply provide the GO_ENV environment variable set to production to your docker container on AWS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM