Using Docker to launch web app, can't connect to Postgresql DB?

后端 未结 4 1344
礼貌的吻别
礼貌的吻别 2021-02-06 10:10

I received the following error when trying to write session data using Tomcat\'s PersistentManager to a Postgres DB running on my local machine:

SEVERE: A SQL e         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-06 10:21

    Why I can NOT connect to localhost:5432?

    Cat your container's /etc/hosts

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

    For docker networks is bridge by default, the localhost inside points to container itself(Docker default bridge network). Then you don't have 5432 listening in your container:

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


    Solution 1. If you wanna hardcode the "localhost:5432" inside your config xml, the easiest way is creating your container with the option "--net=host":

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

    Solution 2. Change the localhost of your docker host ip inside the container

    • Get your docker host ip
      $ sudo docker inspect -f '{{ .NetworkSettings.Gateway }}' 
      192.168.5.1
    • Enter your container:
      $ sudo docker exec -it [container] /bin/bash
    • Edit the file /etc/hosts to point the localhost to docker host ip:
      $ sudo vim /etc/hosts
      192.168.5.1 localhost

    Solution 3. Modify your db config file to use an alias instead of localhost:

    connectionURL="jdbc:postgresql://DB_ALIAS/admin?stringtype=unspecified"
    Then add the DB_ALIAS to the container's hosts :
    $ sudo docker run --add-host DB_ALIAS:192.168.5.1 -it [image] ...
    

提交回复
热议问题