+-
使用Docker启动Web应用程序,无法连接到Postgresql DB?
尝试使用Tomcat的PersistentManager将会话数据写入我的本地计算机上运行的Postgres数据库时收到以下错误:

SEVERE: A SQL exception occurred org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

应用程序本身在docker容器中运行.为了完整起见,我当前的context.xml文件是:

<?xml version='1.0' encoding='utf-8'?>
<Context>
<Manager className="org.apache.catalina.session.PersistentManager"
    distributable="true"  processExpiresFrequency="6" maxIdleBackup="0" debug="99" >
    <Store className="org.apache.catalina.session.JDBCStore"
        driverName="org.postgresql.Driver"
        connectionURL="jdbc:postgresql://localhost/admin?stringtype=unspecified"
        connectionName="admin" connectionPassword="admin"
        sessionAppCol="app_name" sessionDataCol="session_data" sessionIdCol="session_id"
        sessionLastAccessedCol="last_access" sessionMaxInactiveCol="max_inactive"
        sessionTable="tomcat_sessions_tb" sessionValidCol="valid_session" />
</Manager>
</Context>

根据这里的建议:Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

我通过netstat -aln确认了grep LISTEN表示Postgresql正在运行并正在侦听正确的端口:

tcp4       0      0  127.0.0.1.5432         *.*                    LISTEN     
tcp6       0      0  ::1.5432                                      *.*                                           LISTEN     

我的postgresql.conf(位于usr / local / var / postgres中)有listen_addresses = localhost和port = 5432,它反映了我在Pgadmin3中运行的服务器的主机和端口.

我怀疑问题是Docker在VM中运行,因此我获得的本地信息可能不是全部.在线阅读可用信息,似乎我可能需要某种桥接网络,但我承认我是这方面的新手,我不确定如何设置它.

最佳答案
为什么我无法连接到localhost:5432?

捕捉容器的/ etc / hosts

$sudo docker exec -it [container] cat /etc/hosts

对于docker网络默认是桥接,localhost inside指向容器本身(Docker default bridge network).
然后你没有5432在你的容器中听:

$sudo docker exec [container] nc -v -z localhost 5432

解决方案1.如果您想在config xml中对“localhost:5432”进行硬编码,最简单的方法是使用选项“–net = host”创建容器:

$sudo docker run --net=host -it ...

解决方案2.在容器内更改docker host ip的localhost

>获取您的docker主机ip:

$sudo docker inspect -f '{{ .NetworkSettings.Gateway }}' 
192.168.5.1

>输入您的容器:

$sudo docker exec -it [container] /bin/bash

>编辑文件/ etc / hosts以将localhost指向docker host ip:

$sudo vim /etc/hosts
192.168.5.1 localhost

解决方案3.修改db配置文件以使用别名而不是localhost:

connectionURL="jdbc:postgresql://DB_ALIAS/admin?stringtype=unspecified"

然后将DB_ALIAS添加到容器的主机:

$sudo docker run --add-host DB_ALIAS:192.168.5.1 -it [image] ...
点击查看更多相关文章

转载注明原文:使用Docker启动Web应用程序,无法连接到Postgresql DB? - 乐贴网