Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access local postgres database from podman container during build

I have a Spring Boot application that runs inside a container and needs to connect to a local Postgresql database. Now it fails at build time, as that is the moment when it tries to configure Spring beans and to connect to database.

I have configured it like following:

spring  
  datasource:
    initialization-mode: always
    platform: postgres
    url: jdbc:postgresql://192.168.122.1:5432/academy
    username: myuser
    password: mypassword

but it fails to connect.

How shall I configure Dockerfile/connection string?

like image 618
csm86 Avatar asked Dec 01 '25 20:12

csm86


1 Answers

I think you have at least two alternatives

Alternative 1: Connecting via Unix domain socket

If you could have Postgres listen on a Unix domain socket, you could then pass in that socket to the container with a bind-mount. Use podman run with one of the command-line arguments --volume or --mount.

Maybe something like:

--mount type=bind,src=/path/to/socket/on/host,target=/path/to/socket/in/container

If your system has SELINUX enabled, you would need to add the option Z

--volume /path/to/socket/on/host:/path/to/socket/in/container:Z

Alternative 2: Connecting via TCP socket

I think you could add the option

--network slirp4netns:allow_host_loopback=true

to the podman run command and connect to the IP address 10.0.2.2.

Quote "Allow the slirp4netns to reach the host loopback IP (10.0.2.2, which is added to /etc/hosts as host.containers.internal for your convenience)" from the podman run man page. See also slirp4netns.1.md.

(The IP address 10.0.2.2 is a default value hard coded in the source code of slirp4netns).

Here is an example of a container that connects to a web server running on localhost:

esjolund@laptop:~$ curl -sS http://localhost:8000/file.txt
hello
esjolund@laptop:~$ cat /etc/issue
Ubuntu 20.04.2 LTS \n \l

esjolund@laptop:~$ podman --version
podman version 3.0.1
esjolund@laptop:~$ podman run --rm docker.io/library/fedora cur-l -sS http://10.0.2.2:8000/file.txt
curl: (7) Failed to connect to 10.0.2.2 port 8000: Network is unreachable
esjolund@laptop:~$ podman run --rm --network slirp4netns:allow_host_loopback=true  docker.io/library/fedora curl -sS http://10.0.2.2:8000/file.txt
hello
esjolund@laptop:~$ 
like image 163
Erik Sjölund Avatar answered Dec 03 '25 22:12

Erik Sjölund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!