如何将本地托管的 MySQL 数据库与 docker 容器连接

2021-12-07 00:00:00 docker docker-compose mysql

通过 docker-compose.yml 我能够运行该应用程序.现在我们想将应用程序移至生产环境,但我们不想使用容器数据库.那么有什么方法可以让我使用 docker-compose 将我的本地 MySQL 数据库与应用程序连接起来?

Through docker-compose.yml I am able to run the application. Now we want to move the application to production, But we don't want to use the container database. So is there any way so that I can connect my local MySQL database with the application using docker-compose?

我的 docker-compose.yml 看起来像:

My docker-compose.yml looks like:

version: '3'
services:
  web-app:
    build:
      context: .
      dockerfile: web-app/Dockerfile
    ports:
      - 8080:8080
    links:
      - app-db

  app-db:
    build:
      context: .
      dockerfile: app-db/Dockerfile

    environment:
    - MYSQL_ROOT_PASSWORD=password
    - MYSQL_DATABASE=Optimize
    ports:
      - 3306:3306

我只想连接到本地托管的 mysql 数据库,而不是 app-db 部分.

Instead of app-db part I just want to connect to my locally hosted mysql database.

推荐答案

在docker网络中查找宿主机ip.如果你使用 docker-compose.yml version: "3" 那很可能是那个 IP 是:172.18.0.1,但是确认它搜索您的容器(您的主机)的网关":

Find the host machine ip in the docker network. If you use docker-compose.yml version: "3" it's probably that that IP is: 172.18.0.1, but confirm it searching for the "Gateway" of your container (your host):

docker inspect <container-id-or-name> | grep Gateway
"Gateway": "",
            "IPv6Gateway": "",
            "Gateway": "172.18.0.1",
            "IPv6Gateway": "",

因此在您的 docker 应用程序中指向 MySQL 如下:172.18.0.1:3306(可能在配置文件中).考虑到该 IP 是固定的,只要 docker 网络仍然相同(网络是由 docker-compose 创建的,除非您执行 docker-compose down),否则不会删除它

So inside your docker application point to MySQL as this: 172.18.0.1:3306 (maybe in a configuration file). Take into account that that IP is fixed as long as the docker network still the same (the network is created by docker-compose, and it is not removed unless you do docker-compose down)

另外,检查您的 MySQL 是否正在侦听其所有接口.在您的 my.cnf 中搜索 bind-address 应该是 0.0.0.0(如果您的服务器有公共 IP,请考虑安全问题).

Also, check that your MySQL is listening to all of its interfaces. In your my.cnf search for bind-address that should be 0.0.0.0 (consider security issues if your server has public IP).

作为替代方案,您可以将与主机相同的网络连接到容器中,以便共享本地主机,因此容器将在那里找到 mysql.使用网络模式作为主机":

As an alternative you can bring to the container the same networking as your host, in order to share the localhost, so the container will find mysql there. Use network mode as "host":

version: '3'
services:
  web-app:
    build:
      context: .
      dockerfile: web-app/Dockerfile
    ports:
       - 8080:8080
    network_mode: "host"

然后,将您的 hibernate.properties 指向 mysql,如下所示:localhost:3306

Then, point in your hibernate.properties to mysql as this: localhost:3306

相关文章