database - 如何从容器内部访问主机上运行的数据库?

标签 database docker localhost docker-compose

我在容器中运行我的应用程序并映射 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/

相关文章:

javascript - 同一个本地主机端口上的 Web 服务和 Javascript 请求

javascript - 如何让本地js文件工作?

android - 我正在使用 SQLCIPHER 读取或写入数据库时​​出错

Python Sqlite3 : Create a schema without having to use a second database

docker - 使用Docker的Kubernetes无法从默认端口80更改

docker - 无法使用 dockerfile 在容器中移动文件

docker - 在 Windows Docker 容器中附加到 PATH

mysql - 如何从数据库mysql中选择特定列中具有相同且最新值的所有行

mysql - 需要帮助安装 MySQL

url-rewriting - 如何更改 Laravel 的本地主机 url