How to Create and Load a Second Database in ddev for Your Drupal Project (MySQL/MariaDB)
Steps:
-
Import the Database Schema (Recommended):
-
Optional: Manual Database Creation (Less Common):
Using the Second Database in Drupal:
-
Update your Drupal settings to point to the newly created database:
-
In your
settings.php
file, locate the database configuration section:$databases['default']['default'] = [ 'driver' => 'mysql', 'database' => 'my_second_db', 'username' => 'db', 'password' => 'db', 'host' => 'db', 'port' => 3306, ];
-
-
ddev drush cc all
Additional Considerations:
- For complex database setups, consider using Drupal's multisite functionality to manage multiple Drupal installations on the same codebase but with separate databases.
ddev import-db --target-db=my_second_db --file=path/to/your_dump.sql.gz
- Replace
my_second_db
with your desired database name (e.g.,drupal_staging
). - Replace
path/to/your_dump.sql.gz
with the actual path to your database schema file (e.g.,/path/to/project/dumps/drupal_staging.sql.gz
).
Connecting to MySQL within ddev:
ddev ssh mysql -uroot -proot
Inside the MySQL container:
CREATE DATABASE my_second_db; # Create the database
GRANT ALL PRIVILEGES ON my_second_db.* TO 'db'@'%'; # Grant permissions for the 'db' user
Updating Drupal Settings (settings.php):
$databases['default']['default'] = [
'driver' => 'mysql',
'database' => 'my_second_db', # Replace with your second database name
'username' => 'db',
'password' => 'db',
'host' => 'db',
'port' => 3306,
];
Clearing Drupal Caches:
ddev drush cc all
-
Using Environment Variables: Instead of hardcoding the database name in your
settings.php
, you can leverage environment variables. This promotes better code management and easier switching between environments.-
DB_NAME=my_second_db
-
mysql drupal mariadb