You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Docker部署Drupal时出现连接拒绝错误求助

解决Docker环境下Drupal连接MySQL被拒绝的问题

核心问题定位

你的Drupal容器无法连接到MySQL,最直接原因是数据库连接配置中的Host地址错误:在Docker容器内部,127.0.0.1指向容器自身,而非宿主机或MySQL容器。Docker Compose中,服务间可通过服务名(即mysql)直接通信。

分步解决方案

1. 修正Drupal数据库连接配置

修改settings.local.php中的host字段为服务名mysql:

$databases['default']['default'] = [
    'database' => 'gcpc',
    'username' => 'root',
    'password' => 'root',
    'host' => 'mysql', // 替换原127.0.0.1
    'port' => '3306',
    'driver' => 'mysql',
    'prefix' => '',
    'collation' => 'utf8mb4_general_ci',
];

$config['system.logging']['error_level']='verbose';

2. 验证MySQL环境变量配置

确保你的.env文件包含以下关键配置,否则MySQL容器初始化时不会创建指定数据库或设置正确密码:

MYSQL_ROOT_PASSWORD=root
MYSQL_DATABASE=gcpc

若之前已启动过MySQL容器,需删除本地挂载的./mysql目录(数据库初始化仅执行一次),再重新启动容器:

rm -rf ./mysql
docker-compose down
docker-compose up -d

3. 处理MySQL启动延迟问题

depends_on仅保证容器启动顺序,但MySQL可能需要几秒才能完全就绪。可通过以下方式解决:

  • 手动等待30秒左右,待MySQL容器完全启动后再访问Drupal
  • 给Drupal容器添加启动等待脚本(需在容器内安装wait-for-it),修改docker-compose.yml中drupal服务的配置:
drupal:
    image: drupal:php8.2-fpm
    container_name: drupal
    depends_on:
        - mysql
    restart: unless-stopped
    volumes:
        - ./web:/var/www/html
        - ./vendor:/opt/drupal/vendor
        - ./composer.json:/opt/drupal/composer.json
        - ./composer.lock:/opt/drupal/composer.lock
    links:
        - mysql
    command: sh -c "apt-get update && apt-get install -y wait-for-it && wait-for-it mysql:3306 -t 60 && docker-php-entrypoint php-fpm"

4. 检查Nginx配置正确性

确保nginx/default.conf中正确配置FastCGI转发到Drupal容器:

server {
    listen 80;
    server_name localhost;
    root /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass drupal:9000; # 指向drupal服务的9000端口(php-fpm默认端口)
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

验证步骤

  1. 重新启动所有容器:docker-compose down && docker-compose up -d
  2. 查看MySQL容器日志确认正常启动:docker logs mysql,日志中出现ready for connections即表示就绪
  3. 访问http://localhost,检查Drupal是否能正常连接数据库

内容的提问来源于stack exchange,提问作者The_Thinker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:05:02