如何在 DropWizard 应用程序的 docker 容器内的本地计算机上使用 MySQL 服务器 运行?

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

我是 Docker 的新手,目前正在努力将我的 dropwizard 应用程序容器化。每次我构建容器 运行 它并检查日志时,我都会收到 MySQL 连接失败错误,这对于虚拟机上的容器 运行s 来说是有意义的,对于它来说localhost URL 没有任何意义。我想知道如何才能让我的 MySQL 在我的 docker 容器内可访问。谢谢。这就是我的 config.yml 文件的样子 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" ```

假设你有一个 mysql 容器暴露端口 3306 和你的 dropwizard 容器。

您可以为他们创建网络

docker network create <network_name>

并将其分配给 dockers

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

这应该能让那个机器人 docker 看到对方

你可以看到你使用docker network ls的网络如果你使用docker-compose它会自动生成网络。

您还可以使用 host 网络,这也使它们能够连接到您机器中的端口(如果您是 运行 docker 中的虚拟机之一)