首页 > 解决方案 > Laravel Docker 容器无法连接到远程 AWS RDS 数据库

问题描述

我正在使用一个容器化的 Laravel 应用程序,该应用程序应该连接到远程 rds 数据库,这是一个示例 .env

DB_HOST=xxxxxx.rds.amazonaws.com
DB_DATABASE=sample
DB_USERNAME=sample
DB_PASSWORD=sample
DB_PORT=3306
DATABASE_DRIVER=mysql

容器可以正常工作,但问题是,当我尝试运行 composer 时,它无法连接到远程 rds 数据库,即:

$ docker exec -ti laravel-php bash
$ composer install

我收到此错误:

[PDOException]
SQLSTATE[HY000] [1045] Access denied for user 'sample'@'192.168.66.1' (using password: YES)  
                                                                                                        

Script php artisan clear-compiled handling the post-install-cmd event returned with error code 1

192.168.66.1 作为我的 docker 容器的 ip,我怀疑数据库策略是通过 @localhost 访问打开的,因为我的开发操作确认它对公共连接开放。

我正在使用 docker-compose 版本 2 btw,这是一个示例 docker-compose:

version: '2'
services:

    sample-server:
        build:
            context: ./
            dockerfile: sample.server.docker
        volumes:
            - ../backend:/var/www
        ports:
            - "8081:80"
        environment:
            - VIRTUAL_HOST=sample.local
        links:
            - sample-php
        depends_on:
            - sample-php
    sample-php:
        build:
            context: ./
            dockerfile: sample.php.docker
        volumes:
            - .:/var/www
        links:
            - sample-database
        environment:
            - "DB_PORT=3306"
            - "DB_HOST=sample-database"
    sample-database:
        image: mysql:5.7
        environment:
            - "MYSQL_ROOT_PASSWORD=samplepassword"
            - "MYSQL_DATABASE=sample"
        ports:
            - "33081:3306"
    sample-nginx-proxy:
        image: jwilder/nginx-proxy
        ports:
            - "80:80"
        volumes:
            - /var/run/docker.sock:/tmp/docker.sock:ro
networks:
    default:
        external:
            name: sample-nginx-proxy

我怎样才能解决这个问题?

标签: mysqllaraveldockerdocker-composeamazon-rds

解决方案


检查以下内容:

数据库可公开访问: 在数据库所在的 VPC 外部进行连接,更具体地说是通过 Internet 访问,需要将数据库配置为可公开访问。你说的已经完成了。由于您有一个内部 IP,而数据库没有公共 IP,因此这并不是必需的。

基本配置: 检查数据库名称和端口是否设置正确,我相信你已经完成了。

安全组入站规则: 这是最有可能的情况,数据库会有一个或多个安全组。确保在您的情况下将安全组配置为允许来自客户端的入站访问:192.168.66.1

确认客户端的IP地址: 192.168.66.1是容器的陌生IP,VPC子网的前4个IP地址是保留的。

确认网络路由: 确认包含客户端的VPC可以连接到数据库。由于客户端在 docker 容器中运行,请确保容器可以访问数据库。简单的方法是在数据库子网中的 EC2 实例上启用 ICMP 数据包,并检查您是否可以 Ping 它或使用 VPC 路由分析器

检查数据库用户权限: 数据库用户可以连接任何地址而不是localhost

VPC 上的安全性: 检查入站和出站子网的ACL

更新:这是来自AWS的链接:Amazon RDS 故障排除。


推荐阅读