在 Podman 容器构建过程中访问本地的 PostgreSQL 数据库

3

我有一个运行在容器中的Spring Boot应用程序,需要连接到本地Postgresql数据库。现在它在构建时失败了,因为在那个时刻它尝试配置Spring beans并连接到数据库。

我已经按照以下方式进行了配置:

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

但它连接失败了。

我该如何配置Dockerfile/连接字符串?

1个回答

4

我认为你至少有两个选择:

选择1:通过Unix域套接字连接

如果您可以让Postgres监听Unix域套接字,那么您可以将该套接字传递给绑定挂载的容器。使用 podman run 和命令行参数--volume--mount

可能像这样:

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

如果您的系统启用了SELINUX,则需要添加选项Z

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

选择2:通过TCP套接字连接

我认为您可以在podman run命令中添加选项

--network slirp4netns:allow_host_loopback=true

并连接到IP地址10.0.2.2

podman run man页面引用:“允许slirp4netns访问主机回环IP(10.0.2.2,为方便起见添加到/etc/hosts作为host.containers.internal)”。 另请参见slirp4netns.1.md

(IP地址10.0.2.2是硬编码在slirp4netns的源代码中的默认值)。

以下是连接到本地主机上运行的Web服务器的容器示例:

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:~$ 

魔法数字10.0.2.2是从哪里来的? - meolic
"允许slirp4netns访问主机环回IP(10.0.2.2,为方便起见,已添加到/etc/hosts作为host.containers.internal)" 来自podman-run.1.md。另请参阅slirp4netns.1.md - Erik Sjölund
仍然无法正常工作,在podman版本3.4.2上。主机是MacOS。 - Milad
结果证明,至少在我的情况下,这是一个错误 - 是我自己创建的,并且将在下一个3.4版本中修复,详见https://github.com/containers/podman/issues/12507。 - Milad
VirtualBox:在NAT模式下使用的虚拟DHCP服务器的默认地址是10.0.2.2(这也是虚拟机的默认网关IP地址) - Sergio Ocón-Cárdenas
我认为 10.0.2.2 中的最后一位数字 2 来自于这段源代码 https://github.com/rootless-containers/slirp4netns/blob/462be177a5282a7dc76b2308a55b745ef9d50d2d/main.c#L30 - Erik Sjölund

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接