Connecting PHP code on Compute Engine to Cloud SQL

2019-09-01 10:23发布

问题:

I'm trying to connect drupal cms running on a Compute Instance to Cloud SQL database but every combination I try fails. I can connect to Cloud SQl from another server but I'm not sure what path the MySQL connection takes from my instance to Cloud SQL but also want to configure as secure as possible connection to and from the db server

Here is the configuration I have

Servers

  • Cloud SQL with external IP address assigned. Also authorized external IP address of compute instance & Independent Server's IP address to connect.
  • Compute Instance with external IP address running apache & php successfully on the internet
  • Trying to configure database connection from web browser as per step 4 of https://drupal.org/documentation/install/run-script for drupal code running on compute instance
  • Independent Server with internet accessible IP address

Users

  • SQL Root user password set and successfully used to connect from Independent Server using Workbench
  • Db User from host % created to access drupal database and can successfully connect from Independent Server using workbench
  • Same DB user wont connect from compute instance

Networking

  • Running ifconfig on compute instance only shows private Ip address
  • I have opened 3306 on the Google firewall and the instance firewall

My question is how do I get the compute instance to connect to cloud SQL by supplying the dbname, dbusername, dbuserpwd,host(IPAddress) so that it connects exactly like workbench but still have as restricted as possible? Does the issue lie with the configuration of the compute instance, the connection settings used supplied or cloud sql

回答1:

It looks to be a combination of a drupal issue where the host value is discarded or omitted by the installer and an SELinux protection enforcement issue that restricts remote db connections from CentOS which is the guest OS I was using

There is also may be a need to relabel files with their correct SELinux label after adding them to the web root folder

To resolve it: Edit the drupal 7 settings.php yourself to include a mysql connection

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpassword',
      'host' => 'CloudSQLIPAddress',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

and from ssh inside the GCE instance running CentOS run the command below to allow db connections out, I don't think this setting will survive a server reboot but I can live with it for my needs

 setsebool httpd_can_network_connect_db=1

To reapply SElinux context to copied files run this

restorecon -rv /var/www/html