connecting tomcat webapp running in docker contain

2019-05-10 20:48发布

问题:

I have mysql server running in centos host and I want to deploy my war in tomcat inside docker container in same host. Any idea how can I connect mysql from inside the container.

回答1:

Here is what you can do to connect to the DB (mysql) from the App (tomcat). There are two ways you can do this

  1. By using links
  2. Manual way by providing the IP address of db to the tomcat app

Example-1 (Links)

  • Get your mysql container up:

"docker run --name db -e MYSQL_ROOT_PASSWORD="xxxx" -e MYSQL_DATABASE="xxxx" -d mysql"

  • You now need to build and run the application container which must know where is the db instance. You will have to figure out where you provide the link to the db in your application. It can be in the code or in a property file. You can use volume to mount this file into the application container. You will also be able to modify them on the fly because they will be accessible to you on the host system. This is one example of doing this: docker

docker run -d -p 8080:8080 --name app --link db:db -v $PWD/webapp:/var/lib/tomcat7/webapps/ app

  • Here we are using the image app where i am mounting webapp folder from my docker base folder. This folder is having my code which i am pushing to the tomcat's webapp folder. I am also pushing the properties file to the appropiate location on the container where the mysql connection is mentioned like this : "jdbc.url=jdbc:mysql://db:3306/dbname" . We are mapping port 8080 of the container to the port 8080 of the host. We are mapping container db with container app. This creates an entry on /etc/hosts file - "db ipname". So both containers can communicate with each other even if we restart the db container (which changes the IP). Links will update the host entry with the new IP.

Example 2:

  • Up the db container
  • Get the IP of the db container using this "docker inspect -f '{{ .NetworkSettings.IPAddress }}' container-name/ID"
  • Up the app containers with volumes where you can edit the jdbc url on your host.
  • Change the IP to db container's IP and this should be able to establish the connection

If you want to use Host's mysql

docker run -d --net=host --name app image command

Do let me know if you need any further explanation. You can go through the topics on volumes, links from docker documentation: https://docs.docker.com/



标签: docker