How to connect postgresql with golang in docker


(AkezhanOb1) #1

I want to dockerize my project and connect my golang code with postgresql inside docker container but idk how, I have created separate containers (one for golang and second for Postgres) separately they are running, but idk how to connect them


(Johan Dahl) #2

Hi

I’m really a beginner in using docker but I think this is how to do it

You should inside your golang container be able to connect to the postgres container either by referencing it by the following addresses. If they are on the same network.

container ID
Name
Ip-address

You get these by running

$ docker ps -a

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
39ff0c62c984 mysql:5.7 “docker-entrypoint.s…” 31 hours ago Up 31 hours 0.0.0.0:3306->3306/tcp, 33060/tcp mysql

Here is it a mysql container but the docker id and name is in bold

Getting the ip-addresses can be found by inspecting the network your containers are connected to

$ docker network inspect my-network

Log into your golang container with:

$ docker exec -it my-golang-container /bin/bash

and try ping on one of the above addresses and you will see if it works


(Kristoffer Berdal) #3

To add to Johans answer: I believe you can actually use DNS to look up the IP of a linked container… So in the Go container you should be able to lookup a DNS record for ‘postgres’ if the postgres container is called ‘postgres’.

See https://docs.docker.com/docker-cloud/apps/service-links/#hostnames-vs-service-links