如何从Docker容器中访问位于远程IP上的非容器化数据库?

huangapple go评论62阅读模式
英文:

How to access non containerised DB on remote IP from a docker container?

问题

我正在尝试将Java Web服务打包到Docker中。我在一个VM上托管了一个非容器化的Postgres数据库,而Docker容器中的代码无法连接到数据库。如何解决这个问题?

英文:

I am trying to package Java web services in Docker. I have a postgres DB hosted on a VM (non-containerised) and the code in the docker container is unable to connect to the database. How to do that?

答案1

得分: 1

理论上,spring.datasource.url= jdbc:postgresql://yourIpAddress/nameOfDB 应该可以工作。

但是数据库不会在8080端口运行,所以您需要绑定数据库的端口(对于PostgreSQL是5432,对于MySQL是3306),我不建议将其绑定到80端口,因为那里正在监听所有内容。

如果您正在运行PostgreSQL,它将在5432端口上监听,所以您可以执行 docker run -p 8082:5432 postgres

然后您应该能够通过 jdbc:postgresql://yourIpAddress:8082/nameOfDB 连接到您的主机计算机。

这一切都假设没有其他因素干扰,比如防火墙等。我还不知道您如何配置您的虚拟机。一般来说,您应该首先练习在同一台机器上连接它们,以先了解基本概念。

英文:

Theoretically spring.datasource.url= jdbc:postgresql://yourIpAddress/nameOfDB should work.

But database don't run on 8080 so you need to bind the port of database (for postgres 5432, for mysql 3306) and I wouldnt bind it to 80, where everything is listening.

If you are running postgres it will be listening on 5432 so you can do docker run -p 8082:5432 postgres

Then you should be able to connect to your host computer via jdbc:postgresql://yourIpAddress:8082/nameOfDB

This all assumes nothing else jumps in the way, like firewalls or whatnot. I also don't know how you configured your virtual machine. In general you should practice connecting them on the same machine to get the idea first.

huangapple
  • 本文由 发表于 2020年8月11日 03:09:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63346539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定