I'm relatively new to Docker and I'm trying to deploy a Java Springboot application to a container and a MySQL server to another container then allow for a connection between both containers.
The Java application uses java.sql.DriverManager
to communicate with an instance of a MySQL server hosted locally on my machine in a docker container, the application connects to the MySQL server correctly when executed outside of a docker container, however, when I try to execute a docker container of my Java application I receive this error Communications link failure java.net.ConnectException: Connection refused.
I tried changing the connections URI from jdbc:mysql://127.0.0.1:3306/online_store
to jdbc:mysql://mysql-container:3306/online_store
(Note: mysql-container is the name of my docker container that hosts MySQL server) then rebuilt the docker image and ran the container, and the application was successfully able to connect to the MySQL server, was this supposed to happen? if so, I'd like to know why does running the same Java application on different environments (these environments being my host OS and a docker container) require modification of the MySQL URI although the application in both environments is communicating with the same MySQL server instance.
initializing the connection with the MySQL server:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseConnection {
private static Connection connection;
public static Connection getInstance(){
if(connection == null){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/online_store", "root", "1234"); // this only works correctly if the application is being executed outside of a Docker container
}
catch (Exception e){e.printStackTrace();}
}
return connection;
}
}
Dockerfile:
FROM openjdk:11
ADD out/artifacts/online_store_api_jar/online-store-api.jar online-store-api.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "online-store-api.jar"]
Edit: Here is how I configure the Docker container building and communcation via Windows power shell.
>docker pull mysql:5.7
>docker run --name mysql-container -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=1234 mysql:5.7
>docker build . -t online-store-image
>docker run -p 8080:8080 --name online-store-container --link mysql-container:mysql -d online-store-image