Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerized web app connecting to MySQL DB on host

Tags:

docker

mysql

jdbc

I want to migrate my application deployment to use docker/docker hub. Current production set up is to load balance traffic across 2 Linux servers, running Apache, Tomcat and MySQL. The Java web application connects to a master+slave MySQL DB via JDBC.

To minimize the impact of this change, as a first step I am looking at containerizing the tomcat and web application. Leaving Apache and MySQL running on the host(s) as it does now.

The problem I am encountering is connecting the application, running in the docker container, with the MySQL DB running on the host.

The best I can do at the moment is connect to the docker container, get it's IP address and then use an SQL GRANT to allow that IP address access to the DB. The trouble with this is that every time you run a container you potentially get a new IP address and therefor have to run a grant each time.

I've been playing around with this stuff for a while and I can't believe there is not a better solution than what I have proposed above.

Anyone done anything like this? Anyone got any suggestions as to how to best approach this problem.

Edit It's been suggested that "From inside of a Docker container, how do I connect to the localhost of the machine?" is a duplicate of this - but the underlying problem still exists. Every time I create a Docker container from an image I potentially get an new IP address for the container that needs to be granted access to the DB. I wanted to try and avoid having to do this.

Many thanks

like image 645
YanisTheYak Avatar asked Jun 17 '15 08:06

YanisTheYak


2 Answers

You should use dockerized MySQL server and Docker's link command which connects two containers.

First run your MySQL:

docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql

Then run your app with link:

docker run --name some-app --link some-mysql:mysql -d app-that-uses-mysql

Now you can get database's address and port from environment variables:

docker exec -it some-app printenv

Look for something like: MYSQL_PORT_3306_TCP_PORT. Now you just need to use these variables in your app.

More information on Docker MySQL Repo and Docker docs.

like image 68
neciu Avatar answered Dec 05 '22 20:12

neciu


The SQL GRANT should use the IP from docker0 interface instead of the specific IP from the container.

To find it use:

ifconfig | grep -A 1 docker0

and the IP after inet addr: (most probably it will be 172.17.42.1)

This will allow all containers coming from docker interface.

like image 35
george.yord Avatar answered Dec 05 '22 21:12

george.yord