Docker容器连接本地数据库mysql

首先查找docker的IP, 在终端输入:

ifconfig docker0

输出:

docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.18.0.1  netmask 255.255.0.0  broadcast 172.18.255.255
        inet6 fe80::42:ebff:fed8:9ff5  prefixlen 64  scopeid 0x20<link>
        ether 02:42:eb:d8:9f:f5  txqueuelen 0  (Ethernet)
        RX packets 155413  bytes 76450461 (76.4 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 192249  bytes 384602416 (384.6 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

其中的IP 172.18.0.1就是我们需要找的IP

假设有一个docker-compose.yml, 我们需要将上述IP添加到extra_hosts之下:

version: '3'
services:
  strapi-v4:
    image: naskio/strapi
    restart: always
    container_name: strapi-v4
    ports:
      - '1337:1337'
    environment:
      NODE_ENV: production
      DATABASE_CLIENT: mysql
      DATABASE_HOST: #因为mysql只允许localhost,所以提示我将172.21.0.2设置白名单。 这里就是填写172.21.0.2。
      DATABASE_PORT: 3306
      DATABASE_NAME: strapi
      DATABASE_USERNAME: strapi
      DATABASE_PASSWORD: xxxxxxxxx
      DATABASE_SSL: false # boolean for SSL.
    volumes:
      - /root/strapi/app:/srv/app # create a new project in app volume
    extra_hosts:
      - "host.docker.internal:172.18.0.1"
阅读量: | 柯西君_BingWong | 2023-02-17