dockerdevops

Connect application to database when they are in separate docker containers


Well, the set up is simple, there should be two containers: one of them for the mysql database and the other one for web application.

What I do to run the containers, the first one for database and the second for the app:

docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=db -p 3306:3306 -d mysql

docker run -p 8081:8081 myrepo/myapp

The application tries to connect to database using localhost:3306, but as I found out the issue is that each container has its own localhost.

One of the solution I found was to add the same network for containers using --net and the docker commands happend to be like the following:

docker network create my-network

docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=db -p 3306:3306 -d --net my-network mysql

docker run --net my-network -p 8081:8081 myrepo/myapp

Though, the web application still is not able to connect to the database. What am I doing wrong and what is the proper flow to connect application to database when they are both inside containers?


Solution

  • Well, after additional research, I successfully managed to connect to the database.

    The approach I used is the following: On my host I grabbed the IP address of the docker itself but not the specific container: sudo ip addr show | grep docker0

    The IP address of the docker0 I added to the database connection URL inside my application and thus application managed to connect to the database (note: with this flow I don't add the --net keyword when start container)

    What definitely strange is that even adding shared network like --net=my-nework for both the container didn't work. Moreover I did try to use --net=host to share the host network with container's one, still it was unsuccessful. If there's any who can explain why it couldn't work, please - share your knowledge.