Home > other >  Unable to connect to mysql using jdbc in docker
Unable to connect to mysql using jdbc in docker

Time:02-08

I have the following docker-compose:

version: '3.1'
services:
  db:
    container_name: db
    image: mysql
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=world
    volumes:
      - ./mysql-db/:/docker-entrypoint-initdb.d
    networks:
      - my-network
  app:
    depends_on:
      - db
    container_name: app
    build: App/
    networks:
      - my-network
networks:
  my-network:
    driver: bridge

This builds the mysql image and uses a local file to create the database. I am able to connect to the database through a database client on my host machine. I know the db is running and working with those credentials on port 3306.

App/Dockerfile:

# Build stage
FROM maven:latest AS build
COPY src /app/src
COPY pom.xml /app
# need to assemble to package in plugins
RUN mvn -f /app/pom.xml clean compile assembly:single

# Package stage
FROM openjdk:latest
COPY --from=build /app/target/seMethods-1.0-jar-with-dependencies.jar /usr/local/lib/build.jar
ENTRYPOINT ["java", "-jar", "/usr/local/lib/build.jar"]

This builds the jar file using maven.

App/src/App.java


// sql imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class App 
{
  public static void main( String[] args )
  {
    try {
      String dbUrl = "jdbc:mysql://db:3306/world";
      Connection con = DriverManager.getConnection(dbUrl,"root","password");

      String testStatement = "SELECT * FROM city;";
      PreparedStatement preparedTest = con.prepareStatement(testStatement);
      ResultSet rs = preparedTest.executeQuery();

      while(rs.next()){
        System.out.println(rs.getRow());
      }

    } catch (Exception e) {
      // handle any errors
      System.out.println(String.format("Error: %s", e));
    }
  }
}

When my docker-compose runs, the containers are created although my app stops with the following:

Error: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

How can I connect my db container to app?

CodePudding user response:

You are trying to access a ressource outside your app docker container without having set ports on it. By default as you likely know docker container are insulated from the system, thus you can not access port 3306 from inside the container while you can from your host machine. Add the ports to the docker compose file.

CodePudding user response:

Solved.

When creating the db image, the init file used to generate the inital database took a few seconds to complete. Adding a Thread.sleep() hotfix to the start of my java app allowed the database tables to be created and then I am able to connect.

  •  Tags:  
  • Related