I have been trying to dockerize my web-app and everything has gone (mostly) well so far! Except now I am trying to wire in (sorry if the verbage is incorrect) in postgreql as the application connects to a psql DB for logging in as well as storing things.
I read in a post here on SO that I need to just map the db to my local machine by adding ports: -"5432:5432"
to docker-compose.yml. (here is the referenced question Docker Compose + Postgres: Expose port)
However now I am getting a connection refused error whenever I try to do any action that requires db access.
Here is docker-compose.yml
version: '3.1'
services:
drools-average-docker-app:
image: drools-average-docker-image
build:
context: ./
dockerfile: Dockerfile
ports:
- 8080:8080
db:
image: postgres:11-alpine
environment:
POSTGRES_DB: 'droolsTestDB'
POSTGRES_USER: 'postgres'
POSTGRES_PASSWORD: 'postgres'
ports:
- "5432:5432"
I also read somewhere that it might be iptables
blocking the connection? So just in case, here is iptables.rules
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [8:411]
:TCP - [0:0]
:UDP - [0:0]
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -p icmp -m icmp --icmp-type 8 -m conntrack --ctstate NEW -j ACCEPT
-A INPUT -p udp -m conntrack --ctstate NEW -j UDP
-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j TCP
-A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
-A INPUT -p tcp -j REJECT --reject-with tcp-reset
-A INPUT -j REJECT --reject-with icmp-proto-unreachable
COMMIT
In the comments you write that you use
spring.datasource.url=jdbc:postgresql://localhost/droolsTestDB
to connect to the DB. Change this to
spring.datasource.url=jdbc:postgresql://db/droolsTestDB
and it should work even without exposing port 5432 to the host.
Background: Each docker container has its own network interface that corresponds to localhost
for that particular container. Connecting to localhost
from within a container will therefore not connect to the host or some other container. Since docker-compose
offers automatic DNS resolution, it is easy to refer to other services by their names instead.