I have a Docker Swarm cluster setup with 3 servers(1 manager and 2 workers).
I started a Postgresql service using the command below:
docker service create --name postgresql \
--mount src=pg_data,dst=/var/lib/postgresql/data/pgdata \
-p 6542:5432 \
-e POSTGRES_USER="user" \
-e POSTGRES_DB="db" \
-e POSTGRES_PASSWORD="pass" \
-e PGDATA=/var/lib/postgresql/data/pgdata \
--constraint 'node.role == manager' \
postgres
I also created the data volume previously:
docker volume create pg_data
Now, I have another service that I want to start, which is basically a Java application that I bundled into a Docker image and I want to connect it to the postgresql service. I tried the following combinations for the url:
jdbc:postgresql://172.18.0.1:5432/db (docker_gwbridge)
jdbc:postgresql://172.17.0.1:5432/db (docker0)
jdbc:postgresql://localhost:5432/db
jdbc:postgresql://postgresql:5432/db
Any idea what could work?
You shall use a swarm overlay network
to connect to your database inside swarm mode.
First create the overlay network:
docker network create -d overlay mynet
Then make your postgresql
service use this network:
docker service create --name postgresql \
--mount ... \
--network mynet \
postgres
Then, don't forget to use the same network for your Java application container:
docker service create --name myjavaapp \
--network mynet \
myjavaapp
Then you can connect to your postgresql
through DNS name like:
jdbc:postgresql://postgresql:5432/db
All service's containers in the mynet
network (you can call it as you want, it's just a name reference), have DNS entries corresponding to service name. This is easier than having to retrieve container's IP through docker inspect
before launching your java application.
You can even avoid the publish
port -p 6542:5432
in your postgresql docker service as your probably don't want to expose this to others.
You can have a look at the official doc to better understand networks in swarm mode.
This SO QA also talks about overlay network.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With