简体   繁体   中英

Docker Tomcat container unable to access Postgres container

I have a alpine docker with postgres, with listen address '*' and listening to 5432, which I'm deploying using

docker run -d --name postgres me/postgres:v1

and my tomcat container with oracle jre8, on which I'm deploying my rest web service using:

# Set environment
ENV CATALINA_HOME /opt/tomcat

EXPOSE 8080    

# Launch Tomcat on startup
CMD ${CATALINA_HOME}/bin/catalina.sh run
RUN rm -rf ${CATALINA_HOME}/webapps/docs \
    ${CATALINA_HOME}/webapps/examples \
    ${CATALINA_HOME}/webapps/ROOT

# Deploying war file
ADD myapp.war ${CATALINA_HOME}/webapps/ROOT.war

# Restarting server after deploying
CMD ${CATALINA_HOME}/bin/catalina.sh run

And deploying it with

docker run -d -p 8080:8080 --name tomcat --link postgres:postgres me/tomcat:v1

Both are being executed on my laptop, with IP address 192.168.xx, and I checked the port is listening.

Unfortunately my web service on tomcat cannot connect to the postgres service using

jdbc:postgresql://192.168.x.x:5432/dBName

Alternate I already tried: I launched postgres on it's own port using,

docker run -d -p 5432:5432 --name postgres me/postgres:v1
docker run -d -p 8080:8080 --name tomcat me/tomcat:v1

Then used

jdbc:postgresql://192.168.x.x:5432/dBName

and

jdbc:postgresql://localhost:5432/dBName

but neither seems to work.

In both cases I can see my web server running in tomcat manager, and I am able to access my dB using

psql -h localhost -p 5432 -d dBName -U myUser

as well as pgAdmin.

Any help in resolving this is appreciated.

Solution Update: While using --link, point to postgres (ie, your postgresql container name) instead of IP

jdbc:postgresql://postgres:5432/dBName

Many thanks to @larsks for pointing it out.

While using --link, point to postgres (ie, your postgresql container name) instead of IP

jdbc:postgresql://postgres:5432/dBName

So for a full solution, run your postgresql and tomcat container

docker run -d --name postgres me/postgresql:v1
docker run -d -p 8080:8080 --name tomcat --link postgres:postgres me/tomcat:v1

(Notice here I didn't put port for postgres container since it will already have 5432 exposed internally, unless you want to hit it from outside your host, you don't need to specify a port here)

And your server war file will the jdbc address above, postgres will automatically resolve to the container's IP address when they are linked.

Many thanks to @larsks for pointing it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM