How to connect to an RDS database from Yii2?

落爺英雄遲暮 提交于 2019-12-12 06:36:15

问题


I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. However I received this error: "SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known"

All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],

What could be wrong? Thanks.


回答1:


I am guessing that you want pass db information through environment variables. You may want to try to revise the code as below.

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=',
        'dsn' => 'mysql:host='.$_SERVER['RDS_HOSTNAME'].':'.$_SERVER['RDS_PORT'].';dbname='.$_SERVER['RDS_DB_NAME'],
        'username' => $_SERVER['RDS_USERNAME'],
        'password' => $_SERVER['RDS_PASSWORD'],
        'charset' => 'utf8',
    ],

You can reference http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.RDS.html#rds-external-ec2classic in To configure environment properties section to configure your environment variables. Hope this works.




回答2:


You have 2 times your 'dsn' line and maybe the first one survives, so changing your config to this should work:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],

(In addition I hope you are aware that you have to change RDS_* parameters :D)



来源:https://stackoverflow.com/questions/44424106/how-to-connect-to-an-rds-database-from-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!