我在容器中运行我的应用程序并映射 8080 -> 5000 并且它可以工作。但是我想访问在主机系统上运行而不是在其他容器内运行的 Postgres 数据库。假设 pg 在 postgres://localhost:5434/mydb
上运行——我如何从我的应用容器连接到那个数据库?
这是我的 docker-compose.yml
web:
image: myprofile/myimage:latest
ports:
- 8080:5000
最佳答案
不幸的是,这个问题没有简单的答案。
基本上你有两个选择:
1) 使用 volumes
使套接字在容器中可用。
Databases, such as postgres & mysql, support listening on unix domain sockets instead of TCP sockets. The advantages here are that you can forward unix domain sockets into a container via a volume mount
docker run -v
2) 使用 socat
从套接字提供主机内部的 localhost(127.0.0.1) tcp 连接
For applications which only tcp sockets, I just throw
socat
into the image, and start it up in the background inside the container (having it listen on 127.0.0.1, and forward to the named socket).
主机上的 Localhost 只是本地的。如果您在同一网络命名空间中,则只能共享本地主机。
因此,您可以选择 --net=host
或者不使用 localhost
。
关于database - 如何从容器内部访问主机上运行的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133094/