【问题标题】:Connect to mysql in docker-compose在 docker-compose 中连接到 mysql
【发布时间】:2025-06-19 08:30:01
【问题描述】:

我使用的是 docker-compose 版本 1.21.0。

我已经制作了 docker-compose.yml :

  container_name: web
  image: nginx:latest
  ports:
    - "80:80"
  volumes:
    - ./code:/code
    - ./nginx.conf:/etc/nginx/conf.d/default.conf
  links:
    - php
    - mysql

php:
  container_name: php
  build: .
  volumes:
    - ./code:/code
  environment:
    XDEBUG_CONFIG: remote_host=host.docker.internal
  links:
    - mysql

mysql:
  container_name: mysql
  image: mysql:latest
  ports:
    - "3306:3306"
  volumes:
    - ./storage-mysql:/var/lib/mysql
    - ./conf-mysql:/etc/mysql/conf.d
  environment:
    - MYSQL_ROOT_PASSWORD=passwordz

一切都很好,我可以通过以下方式访问我的 mysql 数据库:

docker exec -it mysql mysql -u root -p

注意,我已经设置了我的 mysql 数据库:

bind-address            = 127.0.0.1

因为我不想将 mysql 暴露在互联网上。

我用 PHP 做了一个简单的表格:

<?php

$link = mysqli_connect("mysql:3306", "root", "passwordz", "testdb");

if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}


$icao = mysqli_real_escape_string($link, $_REQUEST['icao']);
$airfield = mysqli_real_escape_string($link, $_REQUEST['airfield']);
$lati = mysqli_real_escape_string($link, $_REQUEST['lati']);


$sql = "INSERT INTO testdb (icao, airfield, lati) VALUES ('$icao', '$airfield', '$lati')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


mysqli_close($link);
?>

但是在尝试了很多不同的配置后,我在发布后收到了 http 错误消息:

警告:mysqli_connect(): (HY000/2002): Connection denied in /code/insert.php on line 4

我错过了什么吗?我完全迷失了,真的需要帮助。

问候,

【问题讨论】:

    标签: php mysql forms docker docker-compose


    【解决方案1】:

    在 Docker 中,您几乎总是需要将 bind-address 和类似选项设置为 0.0.0.0(“无处不在”),否则服务器将无法从其自己的容器外部访问。

    您可以将 IP 地址添加到 ports: 以将发布的端口附加到特定的主机接口:

    services:
      mysql:
        ports:
          # This binds the published port to the _host's_ localhost
          # interface; it will be reachable from outside Docker on
          # the same host, but not from other hosts
          - '127.0.0.1:3306:3306'
    

    如果您不需要从 Docker 外部访问数据库,您也可以完全删除 ports: 部分。其他容器仍可使用其 Compose 服务名称和标准 MySQL 端口 (mysql:3306) 访问它。

    【讨论】: