We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Improve your Craft CMS skills

Using Craft CMS With MySQL

10 min read
Shape April 2022 HR 201

Craft CMS provides a flexible content management system for building customized sites. To unlock its full potential, pairing Craft with a robust database like MySQL is key. This guide explores the many benefits of using MySQL as the database for Craft installs. Learn how to fully leverage MySQL’s speed, scalability, and reliability to optimize performance. Gain expert tips spanning installation, configuration, optimizations, and troubleshooting for seamlessly integrating MySQL and getting the most out of your Craft CMS website.

Craft CMS pairs well with MySQL, leveraging the database's speed, scalability, and reliability. MySQL optimization techniques like tuning configuration parameters, implementing indexes, and enabling caching and replication can significantly improve Craft performance. Following security best practices and troubleshooting common issues ensures MySQL and Craft work together seamlessly.

Using Craft CMS with MySQL

Overview of Craft CMS and MySQL

Craft CMS is a popular open source content management system (CMS) used to build feature-rich websites and applications. MySQL is a popular open source relational database management system (RDBMS) used to store and manage data. Craft CMS uses a database to store and organize all the content, so pairing it with MySQL allows for fast querying and optimal performance.

The benefits of using MySQL as the database for Craft CMS include speed, scalability, flexibility, and wide community support. MySQL is fast, stable, and reliable which helps deliver snappy page loads. It's also scalable to handle large datasets and traffic spikes. The open source nature provides flexibility to customize and integrate as needed. With MySQL being a popular database, there is extensive documentation and support available.

This section will provide an overview of using MySQL as the database for Craft CMS installs. We'll cover the reasons it's a suitable pairing, how to configure Craft CMS to use MySQL, optimizations for performance, and tips for troubleshooting database issues.

Reasons for Using MySQL with Craft CMS

MySQL is one of the most widely used and battle-tested databases which makes it a great fit as the database engine for Craft CMS. Here are some of the key advantages of using MySQL with Craft:

  • Speed and Performance: MySQL is optimized for speed and provides very fast query responses. This results in improved site performance and page load times. The database cache also improves performance for common queries.

  • Scalability: MySQL handles scaling well and can support large datasets and traffic spikes. This is ideal as your Craft CMS site grows larger over time. Sharding can also be used to scale horizontally.

  • Reliability and Uptime: MySQL has proven reliability even under heavy load. The transactional engine with ACID compliance results in high uptime and data integrity. Replication provides redundancy as well.

  • Flexibility: MySQL is open source and gives you full control to customize and tweak database settings for your specific needs. Queries can also be optimized for faster performance.

  • Ease of Management: MySQL has been around for decades and has many GUI tools available for administration and monitoring. This makes database management easier for the web admin.

  • Developer Support: MySQL has a huge community of developers providing libraries, tools, and documentation. This ecosystem makes development easier when building custom solutions.

  • Cost Effective: As an open source database, MySQL is free to use and avoids the licensing costs of proprietary databases. This results in cost savings, especially for smaller sites.

By leveraging the strengths of MySQL like speed, scalability, and flexibility, it proves to be a great choice as the database engine for Craft CMS installs. The open source nature also provides advantages for customization.

Installing and Configuring MySQL for Craft CMS

Downloading and Installing MySQL

Getting started with MySQL for Craft CMS first requires downloading and installing the MySQL database server. The easiest approach is to download the free and open source MySQL Community Edition directly from mysql.com, which provides installers for Windows, Linux, and macOS. For local development environments, the standalone MySQL installer works well for setting up MySQL server along with handy GUI tools like MySQL Workbench for administration. On live production servers, it's best to install MySQL using the native package manager like apt on Ubuntu or yum on CentOS to integrate closely with the OS.

Some best practices are recommended during the installation process. Using a dedicated system user like 'mysql' to run the service avoids potential security issues that could arise from running as root. Placing the MySQL data files on a dedicated disk partition allows storage to scale as the database grows. Setting an explicit data directory path gives more control rather than relying on default locations.

MySQL Workbench on local dev machines provides a user-friendly way to manage databases, users, and permissions. Once installation completes, the MySQL server will be running as a service in the background, ready for the next steps of configuration tailored for Craft CMS.

MySQL Configuration Considerations

With MySQL installed, it now needs to be properly configured and secured for optimal use with Craft CMS. Ensuring MySQL starts up on boot as a service provides persistence across server restarts. Setting correct file and folder permissions, like assigning ownership to the mysql user, prevents account lockout and access issues. A dedicated Craft CMS database should be created in MySQL along with a restricted user account with privileges only for that database. Avoiding use of the root super admin account in favor of less privileged users follows the principle of least privilege for better security.

Other important configuration settings to consider include increasing the max_allowed_packet value to allow larger asset uploads in Craft, allocating ample memory to innodb_buffer_pool_size based on total database size for caching, and configuring user privileges to prevent the Craft CMS user from making schema changes while retaining read/write access to the Craft database itself. Properly configuring MySQL secures the database while also optimizing performance characteristics for the specific needs of a Craft CMS site.

Securing and Optimizing MySQL

Since the MySQL database stores all of a Craft site's critical data, it's essential to follow security best practices. Securing the powerful root account with a strong password and avoiding its use for everyday tasks reduces exposure. Leveraging user permissions and privileges to restrict accounts only to the databases and tables needed prevents accidental or intentional damage.

Disabling remote root login enforces local connections only through dedicated user accounts. Strong password policies incorporating expiration, history, complexity, and length help thwart brute force attacks.

On the optimization side, analyzing slow queries and performance metrics identifies bottlenecks to fix. Increasing the innodb_buffer_pool_size uses available RAM to cache hot data and index blocks for faster access. Bumping up the query_cache_size improves performance for identical queries by caching results. Pre-generating expensive reports and saving them to tables avoids replication lag from running them on the fly. Adjusting innodb_flush_log_at_trx_commit and isolation levels provide better write performance and concurrency. Combining security hardening techniques with database optimizations delivers the best MySQL performance, stability, and protection for Craft CMS installations.

Connecting Craft CMS to MySQL

Updating Craft CMS Configuration

Once MySQL is installed and configured, the next step is updating Craft CMS to connect to the database. This involves configuring the database credentials within Craft's config files.

The main config file is located at /craft/config/db.php and defines the database connection details. The key settings to update are:

  • 'server' - Set this to the MySQL hostname or IP address. Use localhost for local databases.

  • 'user' - The MySQL user account that Craft should use to connect. This should be a dedicated Craft user.

  • 'password' - The password for the Craft MySQL user account. Use a strong password here.

  • 'database' - The name of the MySQL database you created for Craft.

  • 'tablePrefix' - Optional prefix for Craft database tables. Helps avoid conflicts.

Once these MySQL credentials are updated in the config, Craft will be ready to connect to the database.

Pointing Craft CMS Install to MySQL

For brand new Craft CMS installs, you can specify MySQL as the database platform during the initial installation process.

The Craft web-based installer will prompt for database settings. Simply enter the MySQL credentials that were configured earlier - hostname, database name, user, password etc.

The installer will automatically create the database tables and seed the database. So there is no need for any manual table creation.

If using the command line installer, provide the --db-driver=mysql parameter and pass the other database credentials as additional parameters. This will both install Craft and configure it to use the MySQL database in one step.

Testing the MySQL Connection

Verifying that Craft can successfully connect to MySQL is straightforward. With the credentials updated, just navigate to any page in the Craft admin panel.

Craft will attempt to connect to MySQL with those credentials. Any issues will be reported on the page or in the Craft logs.

Some tips for troubleshooting connection problems:

  • Double check credentials are correct in the Craft config files.

  • Try connecting to the MySQL database from command line using the same credentials to isolate issues.

  • Check that the MySQL user has privileges granted for the Craft database.

  • Make sure the Craft database exists in MySQL and inbound connections are allowed.

  • Try flushing privileges and restarting MySQL.

  • Disable firewalls temporarily as a test.

Once the connection settings are validated and working, the site will function as expected with MySQL managing all the Craft CMS content.

Optimizing MySQL Performance for Craft CMS

MySQL Configuration Parameters

MySQL provides a multitude of configuration parameters that can be tuned specifically to optimize performance for the read and write patterns typical of a Craft CMS workload. Settings like the innodb_buffer_pool_size control the memory allocated to cache InnoDB data and indexes, so increasing this to 75% or more of total system RAM significantly improves caching and throughput. Bumping up the max_connections value higher than the default allows more concurrent admin users and site visitors for supporting traffic spikes.

For sites hosted on fast SSD storage, raising the innodb_io_capacity setting enables higher IOPS for InnoDB operations like key lookups to leverage that performance. Adjusting the innodb_flush_log_at_trx_commit parameter allows delayed flush writes sacrificing a small amount of data integrity for better write performance. Since Craft CMS repeatedly issues many identical queries, allocating ample query_cache_size allows frequently repeated queries to be served from memory cache. Tuning configuration parameters specifically for the nuances of typical Craft usage patterns helps MySQL deliver optimal performance.

Database Indexing for Performance

Adding appropriate indexes on MySQL tables is crucial for achieving good performance with Craft CMS. Indexes allow commonly queried columns like entry IDs and status values to be rapidly scanned, sorted, and looked up without needing expensive full table scans.

Some best practices include indexing entry ID columns for fast lookups by primary key, indexing status and type columns used extensively in status and type queries, indexing dateCreated and dateUpdated columns used in date range queries, indexing handle and URI columns used throughout Craft routing, and indexing foreign key columns like entryId and authorId to optimize JOIN performance. Prefix indexes on sorting columns also improve performance for partial matches. Properly indexing the MySQL tables to align with Craft CMS's query patterns allows it to efficiently fetch entries, users, assets, and other data to quickly build pages.

Caching and Replication

MySQL includes extensive caching functionality that can dramatically improve performance for read-heavy Craft workloads. The InnoDB buffer pool caches table and index blocks in memory avoiding slow disk I/O. The query cache stores results of repeated identical SQL queries, allowing cached values to be returned without re-running queries. Integrating with Redis provides a fast lookup cache for database queries as well.

Reading from MySQL replicas allows distributing read queries across multiple servers. Near real-time replication ensures replica lag is negligible. Separating reads and writes improves performance isolation. Enabling MySQL's robust caching features and leveraging replication provides further optimization techniques that can massively improve MySQL performance for heavily trafficked Craft sites.

Managing the Craft CMS MySQL Database

Database Structure and Schema

Craft CMS leverages a relational MySQL database to store all its site content, users, and configuration. Some key tables include:

  • craft_entries - Stores all the channel entries with metadata like title, slug, content, etc.

  • craft_assets - Manages all asset files uploaded including images, PDFs, etc.

  • craft_users - Contains user accounts along with profile fields.

  • craft_fields - Defines all custom fields and their settings.

  • craft_relations - Maps relationships between entries, assets, users, and tags.

  • craft_globals - Stores global set content.

These core tables are related via foreign keys to build the full content structure. Additional tables handle plugin storage, configuration settings, queues, and logging.

Running and Reverting Migrations

When updating Craft CMS or installing new plugins, database migrations need to be run to safely update the database schema.

The craft migrate/all command runs all new migrations to create or alter tables as needed. Rollback commands like craft migrate/down can revert previously applied migrations.

Craft tracks all migration change history in the craft_migrations table. This provides visibility into schema changes over time and makes it easy to return to a previous state if needed.

Following proper migration practices avoids manual schema changes and keeps all environments synchronized.

Multi-environment Syncing

For best practices, Craft CMS should utilize separate databases for each environment like development, staging, and production. This isolates data between environments.

To sync them, tooling like Deployer can be used to push only code migrations between environments. Then data can be selectively synced like assets and users.

Another approach is using dbdump files to "push" production data "downstream" to staging and dev environments regularly. This avoids manually exporting and importing the full database each time.

Scheduling migrations and data syncs overnight helps minimize site disruption. Utilizing separate databases per environment while regularly syncing key data helps maintain up-to-date schemas and content.

MySQL User Accounts and Security for Craft CMS

MySQL User Permissions

Properly configuring user accounts and permissions is crucial for securing MySQL access for Craft CMS.

Dedicated Craft MySQL users should be granted the minimum privileges required, ideally only allowing read/write access to the Craft database. Avoid using the 'root' super admin account for daily operations.

The principle of least privilege limits damage from compromised credentials. Craft admins should not have schema modification or user administration privileges which could be abused.

Revoking unwanted permissions and enabling blocklists for key tables provide additional hardening. Workstations should only allow local connections, with remote access disabled.

Overall, tightly restricting user privileges and avoiding blanket permissions are key MySQL security measures for Craft installs.

Password Management

Strong password policies should be enforced for MySQL accounts:

  • Require minimum 15+ character passwords with complexity rules.

  • Expire passwords every 90 days forcing rotation.

  • Maintain password history to prevent reuse.

  • Securely transmit and store credentials via encryption.

  • Use single-sign-on (SSO) where possible to avoid hard-coded passwords.

  • Rotate Craft admin passwords if a MySQL user credential is compromised as a precaution.

Proper password hygiene prevents brute force, unauthorized access, and account takeovers.

Backup and Recovery

Scheduled MySQL backups are essential for Craft CMS disaster recovery:

  • Automate daily or weekly database dumps and store securely off-site.

  • Take full and incremental backups to enable point-in-time restores.

  • Test restores on dev servers periodically to validate backups.

  • For quick restores, maintain a replica database server as a warm standby.

  • Backup both database files and binary logs to sync data and logs.

With robust backup procedures in place, failed servers or corruption issues can be recovered from backups within the needed RTO and RPO.

Hardening MySQL security along with consistent backup processes give confidence to recover from any catastrophic failures for business continuity.

Troubleshooting Common MySQL Issues with Craft CMS

Memory and Performance Issues

Slow MySQL performance issues frequently impact Craft CMS installs and can stem from various causes. Insufficient memory allocated to the InnoDB buffer pool results in increased disk I/O as data cannot be cached effectively in RAM. Missing indexes on tables used in common Craft queries forces full table scans rather than fast index lookups.

Setting the max_connections value too high can overwhelm resources when concurrent admin and visitor traffic spikes. Small configuration values like tmp_table_size can limit cache usage for temporary tables and sorting. Un-optimized queries that don't utilize available indexes properly also lead to poor performance.

Techniques for diagnosing these performance problems include reviewing logs for high disk activity, analyzing key buffer pool hit ratios, tweaking MySQL configuration parameters, adding indexes aligned with typical Craft access patterns, and inspecting slow queries to add hints that force index usage where needed. Taking a structured approach helps troubleshoot and resolve the various potential issues that can result in slow MySQL performance.

Migration and Sync Failures

When running schema migrations or syncing database dumps across environments for Craft CMS, MySQL migration failures can happen for various reasons. Syntax errors in newly applied migration scripts prevent proper execution, resulting in partially completed schema changes.

Conflicts between the existing schema and changes in migration scripts can also cause failures, which may require resetting all environments to a consistent state before re-applying migrations. Large database dumps that exceed the configured max packet size fail to fully migrate. Validation issues due to insufficient user account privileges block access for migrations and syncs. And resource-intensive operations like index rebuilds can time out during migrations.

Careful inspection of error logs coupled with reviewing migration scripts, validating user permissions, and adjusting configurations are techniques that can help troubleshoot and ultimately resolve stubborn migration and sync issues.

Corruptions and Crashes

For Craft's MySQL data, server crashes and data corruptions can occur. Checksum mismatches help identify corrupted tables, which require attempted repairs or extraction of data into new tables. Hardware failures identified in logs may indicate aging disks in need of replacement.

Memory failures detected via memtest86+ or unexpected power issues could point to power supplies or RAM needing replacement to prevent crashes. Restoring from backup dumps and replaying binary logs can recover after crashes or corruption. Regularly testing restores ensures recovery reliability. Setting up MySQL replicas provides faster recovery through promoting a hot standby after outages.

By combining proactive monitoring, backups, and standby servers, recovery can be swift even after crashes or corruption.

Alternative Database Options for Craft CMS


PostgreSQL is a popular open source database that can also be used as the backend for Craft CMS installs.

Some of the advantages of PostgreSQL include:

  • Advanced data types like JSONB for schema flexibility

  • Sophisticated indexing features like partial indexes

  • Excellent scaling capabilities for large datasets

  • Fine-grained user privileges and access controls

The disadvantages compared to MySQL include:

  • Smaller community size results in less support resources

  • Slightly steeper learning curve for new developers

  • Lacks some built-in functionality provided by MySQL

Overall PostgreSQL offers a robust database option for certain use cases where more advanced database functionality is required.

Amazon Aurora

Amazon Aurora provides a fully-managed MySQL compatible database engine on AWS.

For production Craft CMS workloads on AWS, Aurora combines the familiarity of MySQL with key benefits like:

  • Automated scaling, backups, and failover

  • High availability across AZs and read replicas

  • Advanced security protecting sensitive content

  • Improved performance via SSD storage and caching

The tradeoff is reduced control over database server customizations and reliance on Amazon.

Microsoft SQL Server

Microsoft SQL Server offers another enterprise-grade database alternative for Craft installs.

Some potential advantages over MySQL include:

  • Powerful graphical management tools

  • Tight integration with Windows servers

  • Advanced business intelligence features

  • Potential licensing cost savings for existing Windows-heavy infrastructures

Downsides can be higher licensing costs for pure Linux environments, steeper learning curve, and smaller community/support ecosystem.

Overall SQL Server provides a viable alternative to MySQL for the right workloads, balancing pros and cons.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat