首页 > 解决方案 > 在构建期间从 podman 容器访问本地 postgres 数据库

问题描述

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

我已将其配置如下:

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

但它无法连接。

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

标签: postgresqlpodman

解决方案


我认为您至少有两种选择

备选方案 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 套接字连接

我想你可以添加选项

--network slirp4netns:allow_host_loopback=true

podman run命令并连接到 IP 地址10.0.2.2

下面是一个连接到在 localhost 上运行的 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:~$ 

推荐阅读