Let me try explain what i did.
Postgresql
First of all I did the configuration needed to make sure my Postgres Database was accepting connections from outside.
open pg_hba.conf
and add in the end the following line:
host all all 0.0.0.0/0 md5
open postgresql.conf
and look for listen_addresses
and modify there like this:
listen_addresses = '*'
Make sure the line above is not commented with a #
-> Restart your database
OBS: This is not the recommended configuration for a production environment
Next, I looked for my host’s ip
. I was using localhosts ip 127.0.0.1
, but the container doesn’t see it, so the Connection Refused message in question shows up when running the container. After a long search in web about this, I read that the container sees the internal ip from your local network (That one your router attributes to every device that connects to it, i’m not talking about the IP that gives you access to the internet). That said, i opened a terminal and did the following:
Look for local network ip
Open a terminal or CMD
(MacOS/Linux)
$ ifconfig
(Windows)
$ ipconfig
This command will show your network configuration information.
And looks like this:
en4:
ether d0:37:45:da:1b:6e
inet6 fe80::188d:ddbe:9796:8411%en4 prefixlen 64 secured scopeid 0x7
inet 192.168.0.103 netmask 0xffffff00 broadcast 192.168.0.255
nd6 options=201<PERFORMNUD,DAD>
media: autoselect (100baseTX <full-duplex>)
status: active
Look for the one that is active.
In my case, my local network ip was 192.168.0.103
With this done, I ran the container.
Docker
Run the container with the --add-host
parameter, like this:
$ docker run --add-host=aNameForYourDataBaseHost:yourLocalNetWorkIp --name containerName -di -p HostsportToBind:containerPort imageNameOrId
In my case I did:
$ docker run --add-host=db:192.168.0.103 --name myCon -di -p 8000:8000 myImage
I’m using Django
, so the 8000
port is the default.
Django Application
The configuration to access the database was:
In settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': ‘myDataBaseName',
'USER': ‘username',
'PASSWORD': '123456',
'HOST': '192.168.0.103',
'PORT': 5432,
}
}
References
About -p
flag:
Connect using network port mapping
About docker run
:
Docker run documentation
Interesting article:
Docker Tip #35: Connect to a Database Running on Your Docker Host