Search code examples
javamysqldockerdropwizard

How to use the MySQL server running on my local machine inside the docker container for a DropWizard application?


I'm new to Docker and am currently struggling with containerizing my dropwizard application. Each time I build the container, run it, and check the logs, I get the MySQL connection failure error which makes sense as the container runs on a virtual machine and for it the localhost URL means nothing. I was wondering what can I do to make my MySQL accessible inside my docker container. Thanks. This is how my config.yml file looks like rn.

  driverClass: com.mysql.cj.jdbc.Driver
  # the username
  user: root

  # the password
  password:

  # the JDBC URL
  url: jdbc:mysql://localhost:3306/locations?useLegacyDatetimeCode=false&serverTimezone=UTC

  # any properties specific to your JDBC driver:
  properties:
    charSet: UTF-8

  # the maximum amount of time to wait on an empty pool before throwing an exception
  maxWaitForConnection: 1s

  # the SQL query to run when validating a connection's liveness
  validationQuery: "/* MyService Health Check */ SELECT 1"

  # the timeout before a connection validation queries fail
  validationQueryTimeout: 3s

  # the minimum number of connections to keep open
  minSize: 8

  # the maximum number of connections to keep open
  maxSize: 32

  # whether or not idle connections should be validated
  checkConnectionWhileIdle: false

  # the amount of time to sleep between runs of the idle connection validation, abandoned cleaner and idle pool resizing
  evictionInterval: 10s

  # the minimum amount of time an connection must sit idle in the pool before it is eligible for eviction
  minIdleTime: 1 minute

  # Logging settings.
#logging:
#  level: INFO
#  loggers:
#    io.dropwizard: DEBUG
#    org.eclipse.jetty.servlets: DEBUG
#    org.hibernate.SQL: ALL
#    com.udemy.LocationsApplication:
#      level: ALL,
#      additive: false
#      appenders:
#        - type: conso
#          logFormat: "%red(CDR) [%magenta(%date)] [%thread] [%cyan(%logger{0})]: %message%n"
#  appenders:
#    - type: console
#      logFormat: "%highlight(%-5level) [%magenta(%date)] [%thread] [%cyan(%logger{0})]: %message%n" ```

Solution

  • Assuming you have a mysql container exposing the port 3306 and your dropwizard container.

    You can create a network for them

    docker network create <network_name>
    

    And assign it to the dockers

    docker run .... --network <network_name>
    

    This should make that bot dockers see each other

    You can see the networks you have using docker network ls if you use docker-compose it will generate the networks automatically.

    You can also use the host network which also makes them able to connect to ports in your machine (the virtual machine if you are running docker in one of those)