Azure Database for MySQL
Azure Database for MySQL
for MySQL:
Developer Guide
Table of Contents
01 / Azure MySQL Developer Guide ............................................................................................................................................................. 5
02 / Introduction to Azure Database for MySQL ..................................................................................................................................... 7
What is MySQL? ............................................................................................................................................................................................... 7
Comparison with other RDBMS offerings ............................................................................................................................................. 7
MySQL hosting options ................................................................................................................................................................................ 7
Hosting MySQL on Azure - benefits and options .............................................................................................................................. 9
Introduction to Azure resource management ...................................................................................................................................11
Introduction to Azure Database for MySQL .......................................................................................................................................22
Migrate to Flexible Server ..........................................................................................................................................................................27
02 / Summary .................................................................................................................................................................................................28
03 / Getting Started - Setup and Tools......................................................................................................................................................29
Azure free account........................................................................................................................................................................................29
Azure subscriptions and limits .................................................................................................................................................................29
Azure authentication ...................................................................................................................................................................................29
Development editor tools ..........................................................................................................................................................................30
Resources .........................................................................................................................................................................................................31
Create a Flexible Server database ...........................................................................................................................................................31
Connect and query Azure Database for MySQL using MySQL Workbench ..........................................................................32
Connect and query Azure Database for MySQL using the Azure CLI ......................................................................................33
Language support .........................................................................................................................................................................................34
03 / Summary .................................................................................................................................................................................................43
04 / End to End application development ................................................................................................................................................44
Common Azure development services overview .............................................................................................................................44
Introduction to the Sample Application ..............................................................................................................................................48
Deployment evolution options ................................................................................................................................................................49
Classic deployment.......................................................................................................................................................................................50
Azure VM deployment ................................................................................................................................................................................51
Simple App Service deployment with Azure Database for MySQL Flexible Server ............................................................51
App Service with In-App MySQL .............................................................................................................................................................52
Continuous Integration (CI) and Continuous Delivery (CD) .........................................................................................................52
Containerizing layers with Docker ..........................................................................................................................................................53
Azure Container Instances (ACI) ..............................................................................................................................................................53
App Service Containers ...............................................................................................................................................................................54
Azure Kubernetes Service (AKS) ..............................................................................................................................................................54
AKS with MySQL Flexible Server .............................................................................................................................................................55
Start the hands-on-tutorial developer journey .................................................................................................................................56
The topics and flow contained in this guide cover the advantages of migrating to or leveraging various simple to
use, valuable Azure cloud services in MySQL architectures. Be prepared to learn how easy and quick it is to create
applications backed by Azure Database for MySQL. In addition to building customized services, developers will
also be able to leverage the vast number of value-add services available in the Azure Marketplace. Throughout
this developer journey, strive to leverage the vast number of resources presented rather than going at it alone!
Because every company and project is unique, this guide provides insightful service descriptions and tool
comparisons to allow the reader to make choices that fit their environment, system, and budget needs. Proven
industry architecture examples provide best practice jumpstarts allowing for solid architecture foundations and
addressing potential compliance needs.
Development teams will understand best practices and efficient architecture and security practices – avoiding the
problems and costs of poor design. Teams will gain the knowledge to automate builds, package, test, and deliver
applications based on MySQL to various hosting environments. By leveraging continuous integration and
deployment (CI/CD), costs related to manual deployment tasks can be reduced or completely removed.
The ultimate goal is to successfully deploy a stable, performant MySQL application running securely in Microsoft
Azure using cloud best practices. Let’s start the journey!
What is MySQL?
MySQL is a relational database management system based on Structured Query Language (SQL). MySQL supports
a rich set of SQL query capabilities and offers excellent performance through storage engines optimized for
transactional and non-transactional workloads, in-memory processing, and robust server configuration through
modules. Its low total cost of ownership (TCO) makes it extremely popular with many organizations. Customers
can use existing frameworks and languages to connect easily with MySQL databases. Reference the latest MySQL
Documentation for a more in-depth review of MySQL’s features.
One of MySQL databases’ common use cases is the data store for web applications. Due to MySQL’s scalability,
popular content management systems (CMS), such as WordPress and Drupal, utilize it for their data persistence
needs. More broadly, LAMP apps, which integrate Linux, Apache, MySQL, and PHP, leverage scalable web servers,
languages, and database engines to serve many global web services.
While MariaDB is compatible with the MySQL protocol, the project is not managed by Oracle, and its maintainers
claim that this allows them to better compete with other proprietary databases. Although there are several
different options to choose from, MySQL has over twenty years of development experience backing it, and
businesses appreciate the platform’s maturity.
Another popular open-source MySQL competitor is PostgreSQL. MySQL supports many of the advanced features
of PostgreSQL, such as JSON storage, replication and failover, and partitioning, in an easy-to-use manner.
Microsoft offers a cloud-hosted Azure Database for PostgreSQL, which can be compared with cloud-hosted
MySQL in Microsoft Learn.
On-premises
MySQL is a cross-platform offering, and corporations can utilize their on-premises hardware to deploy highly-
available MySQL configurations. MySQL on-premises deployments are highly configurable, but they require
significant upfront hardware capital expenditure and have the disadvantages of hardware/OS maintenance.
Pros
Cons
IaaS lets organizations bypass the cost and complexity of buying and managing physical servers and datacenter
infrastructure. Each resource is offered as a separate service component and only requires paying for resources for
as long as they are needed. A cloud computing service provider like Microsoft Azure manages the infrastructure,
while organizations purchase, install, configure, and manage their software—including operating systems,
middleware, and applications.
Pros
Cons
Containers
While much more lightweight, containers are similar to VMs and can be started and stopped in a few seconds.
Containers also offer tremendous portability, making them ideal for developing an application locally on a
development machine and then hosting it in the cloud, in test, and later in production. Containers can even run
on-premises or in other clouds. This flexibility is possible because the development environment machine travels
with the container. The application runs consistently. Containerized applications are flexible, cost-effective, and
deploy quickly.
Pros
• Application scalability
Cons
• Container monitoring
Cloud PaaS
MySQL databases can be deployed on public cloud platforms by utilizing VMs, container runtimes, and
Kubernetes. However, these platforms require a middle ground of customer management. If a fully managed
environment is required, cloud providers offer their own managed MySQL products, such as Amazon RDS for
MySQL and Google Cloud SQL for MySQL. Microsoft Azure offers Azure Database for MySQL.
By offering solutions on Azure, ISVs can access one of the largest B2B markets in the world. Through the Azure
Partner Builder’s Program, Microsoft assists ISVs with the tools and platform to offer their solutions for customers
to evaluate, purchase, and deploy with just a few clicks of the mouse.
Microsoft’s development suite includes such tools as the various Visual Studio products, Azure DevOps, GitHub,
and low-code Power Apps. These tools contribute to Azure’s success and growth through their tight Azure
platform integrations. Organizations that adopt modern tools are 65% more innovative, according to a 2020
McKinsey & Company report.
To facilitate developers’ adoption of Azure, Microsoft offers a free subscription with $200 credit, applicable for
thirty days; year-long access to free quotas for popular services, including Azure Database for MySQL; and access
to always free Azure service tiers. Create an Azure free account and get 750 hours of Azure Database for MySQL
Flexible Server free.
Because IaaS MySQL hosting gives greater control over the MySQL database engine and the OS, many
organizations choose to lift and shift on-premises solutions while minimizing capital expenditure.
IaaS (Containers)
Although VMs are considered the primary IaaS approach, containerizing MySQL instances and applications can
also be included in this approach. Modernizing applications allows for more opportunities for deployment and
management with Kubernetes and container hosting environments coming into the picture. Azure provides Azure
Kubernetes Service (AKS) and, as explored below, several other PaaS-based approaches to hosting MySQL and
application containers.
PaaS (DBaaS)
In the PaaS model, organizations deploy a fully managed MySQL environment on Azure. Unlike IaaS, they cede
control over patching the MySQL engine and OS to the Azure platform, and Azure automates many administrative
tasks, like providing high availability, backups, and protecting data.
Like IaaS, customers are still responsible for managing query performance, database access, and database objects,
such as indexes. PaaS is suitable for applications where the MySQL configuration exposed by Azure is sufficient,
and access to the OS and filesystem is unnecessary.
The Azure DBaaS MySQL offering is Azure Database for MySQL. This MySQL community edition derivative
supports common administration tools and programming languages.
PaaS (Containers)
In addition to the IaaS and PaaS options mentioned above, it is possible to choose to host container-based
instances inside PaaS-based services such as Azure Container Instances and Azure App Services.
Video reference
For a video comparison of cloud hosting models, please refer to Microsoft Learn.
The Azure Fundamentals Microsoft Learn Module demonstrates how IaaS and PaaS classifies Azure services.
Moreover, Azure empowers flexible hybrid cloud deployments and supports a variety of common tools, such as
Visual Studio, PowerShell, and the Azure CLI, to manage Azure environments.
The following table outlines some of the Azure services used in application developer scenarios that will be
discussed in further detail in later sections of this guide.
• Virtual Machines (IaaS): Begin by running a PHP sample application on an Azure Windows Server Virtual
Machine.
• Azure App Service (PaaS): Deploy the PHP application to Azure App Service, a flexible, simple-to-use
application hosting service.
• Azure Container Instances (PaaS): Containerize apps on the VM to operate in an environment isolated
from other development tools installed on the system. Azure Container Instances provides a managed
environment to operate containers.
• Azure Kubernetes Service (PaaS): AKS also hosts containerized apps, but it is optimized for more
advanced orchestration scenarios, such as high availability.
For a more comprehensive view, consult the Azure Fundamentals Microsoft Learn module.
• Management groups: Management groups consolidate multiple Azure subscriptions for compliance and
security purposes.
• Resource groups: Resource groups consolidate the individual Azure resources for a given deployment. All
provisioned Azure resources belong to one resource group. In this guide, it will be required to provision a
resource group in an subscription to hold the required resources.
– Resource groups are placed in a geographic location that determines where metadata about that
resource group is stored.
• Resources: An Azure resource is an instance of a service. An Azure resource belongs to one resource
group located in one subscription.
To help organizations quickly move to Azure, Microsoft provides the Azure landing zone accelerator, which
generates a landing zone ARM template according to an organization’s core needs, governance requirements, and
automation setup. The landing zone accelerator is available in the Azure portal.
All Azure management tools, including the Azure CLI, Azure PowerShell module, Azure REST API, and browser-
based Portal, interact with the Azure Resource Manager layer and Identity and access management (IAM) security
controls.
Access control to all Azure services is offered via the Azure role-based access control (Azure RBAC) natively built
into the management platform. Azure RBAC is a system that provides fine-grained access management of Azure
resources. Using Azure RBAC, it is possible to segregate duties within teams and grant only the amount of access
to users that they need to perform their jobs.
Azure portal
As a new Azure user, the first resource a person will be exposed to is the Azure Portal. The Azure Portal gives
developers and architects a view of the state of their Azure resources. It supports extensive user configuration and
simplifies reporting. The Azure mobile app provides similar features for mobile users.
Azure runs on a common framework of backend resource services, and every action taken in the Azure portal
translates into a call to a set of backend APIs developed by the respective engineering team to read, create,
modify, or delete resources.
Azure Marketplace
Azure Marketplace is an online store that contains thousands of IT software applications and services built by
industry-leading technology companies. In Azure Marketplace, it is possible to find, try, buy, and deploy the
software and services needed to build new solutions and manage the cloud infrastructure. The catalog includes
solutions for different industries and technical areas, free trials, and consulting services from Microsoft partners.
Evolving
Moving workloads to Azure alleviates some administrative burdens, but not all. Even though there is no need to
worry about the data center, there is still a responsibility for service configuration and user access. Applications
will need resource authorization.
Using the existing command-line tools and REST APIs, it is possible to build custom tools to automate and report
resource configurations that do not meet organizational requirements.
There are subtle differences between how each tool operates and the feature behaviors. Use the Azure command-
line tool guide to determine the right tool to meet the target goal.
Azure CLI
It is possible to run the Azure CLI and Azure PowerShell from the Azure Cloud Shell, but it does have some
limitations. It is also possible to run these tools locally.
To use the Azure CLI, download the CLI tools from Microsoft.
To use the Azure PowerShell cmdlets, install the Az module from the PowerShell Gallery, as described in the
installation document.
PowerShell Module
The Azure portal and Windows PowerShell can manage Azure Database for MySQL instances. To get started with
Azure PowerShell, install the Azure PowerShell cmdlets for MySQL with the following PowerShell command:
After the modules are installed, reference tutorials to learn how to take advantage of scripting management
activities:
Infrastructure as Code
Infrastructure as Code (IaC) provides a way to describe or declare what infrastructure looks like using descriptive
code. The infrastructure code is the desired state. The environment will be built when the code runs and
ARM templates
ARM templates can deploy Azure resources in a declarative manner. Azure Resource Manager can potentially
create the resources in an ARM template in parallel. ARM templates can be used to create multiple identical
environments, such as development, staging, and production environments.
Bicep
Reading, updating, and managing the ARM template JSON code can be difficult for a reasonably sized
environment. What if there was a tool that translates simple declarative statements into ARM templates? Better
By using the Azure CLI it is possible to decompile ARM templates to Bicep using the following:
Additionally, the Bicep playground tool can perform similar decompilation of ARM templates.
Terraform
Hashicorp Terraform is an open-source tool for provisioning and managing cloud infrastructure. Terraform is
adept at deploying infrastructure across multiple cloud providers. It enables developers to use consistent tooling
to manage each infrastructure definition.
Other tips
Azure administrators should consult with cloud architects and financial and security personnel to develop an
effective organizational hierarchy of resources. Here are some best practices to follow for Azure deployments.
• Adopt a naming convention: Names in Azure should include business details, such as the organization
department, and operational details for IT personnel, like the workload.
• Adopt other Azure governance tools: Azure provides mechanisms such as resource tags and resource
locks to facilitate compliance, cost management, and security.
Support
Azure provides multiple support plans for businesses, depending on their business continuity requirements. There
is also a large user community:
• Azure on Twitter
• Move to Azure efficiently with customized guidance from Azure engineers. FastTrack for Azure
Training
• Azure Certifications and Exams
• Microsoft Learn
Azure Database for MySQL supports MySQL Community Editions 5.6, 5.7, and 8.0, making it flexible for most
migrations. Reference the Migrating to Azure Database for MySQL guide for in-depth information and examples
on how to successfully migrate to Microsoft Azure.
Control Plane As the image below demonstrates, Azure Resource Manager handles resource configuration,
meaning that standard Azure management tools, such as the CLI, PowerShell, and ARM templates, are still
applicable. This is commonly referred to as the control plane.
Data Plane For managing database objects and access controls at the server and database levels, standard
MySQL management tools, such as MySQL Workbench, still apply. This is known as the data plane.
Note: This guide will be focused on Flexible Server and will not explore Single Server.
Flexible Server
Flexible Server is also a PaaS service fully managed by the Azure platform, but it exposes more control to the user
than Single Server.
The picture displays the logo for Azure Database for MySQL for Beginner Series.
Watch: Introduction to the Beginners Series [1 of 16] | Azure Database for MySQL - Beginners Series
Watch: Top 3 Reasons to consider Azure Database for MySQL to learn more about Flexible Server’s
advantages.
Cost management is one of the advantages of Flexible Server: it supports a burstable tier, which is based on the B-
series Azure VM tier and is optimized for workloads that do not continually use the CPU. Flexible Server instances
can also be paused. The image below shows how Flexible Server works for a non-high availability arrangement.
Locally-redundant storage replicates data within a single availability zone. Availability zones are present within a
single Azure region (such as East US) and are geographically isolated. All Azure regions that support availability
zones have at least three.
• User-scheduled service maintenance: Flexible Server allows database administrators to set a day of the
week and a time for Azure to perform service maintenance and upgrades, per server. Providing
notifications five days before a planned maintenance event, Flexible Server caters to the needs of IT
operations personnel.
This image demonstrates how to set a custom maintenance schedule in Flexible Server.
• Automatic backups: Azure automates database backups, encrypts them, and stores them for a
configurable period.
• Read replicas: Read replicas help teams scale their applications by providing read-only copies of the data
updated on the master node. Often, applications that run on elastic, autoscaling services, like Azure App
Service, couple well with read replicas.
• Input-output operations per second (IOPS): IOPS can be configured based on your performance needs.
Some of these features are not exclusive to Flexible Server. Further guide sections demonstrate Flexible
Server exposes far more versatility and is the preferred Azure Database for MySQL choice in Azure for new
and existing apps.
• General Purpose: This tier corresponds to a Ddsv4-series Azure VM. Instances provisioned in this tier
have 2-64 vCores and 4 GiB memory per vCore. It is ideal for most enterprise applications requiring a
strong balance between memory and vCore count.
• Business Critical: This tier corresponds to an Edsv4-series and Edsv5-series Azure VMs. Instances
provisioned in this tier have 2-80 vCores and 8 GiB memory per vCore. It is ideal for mission critical, high-
performance, or real-time workloads that depend on in-memory processing.
Note: The Azure TCO Calculator can be used to estimate the cost savings of deploying PaaS Azure
MySQL over the same deployment in an on-premises data center.
2. Indicate the configuration of on-premises hardware and the Azure landing zone, adjust calculation
parameters, like the cost of electricity, and observe the potential savings.
• Support for only the InnoDB and MEMORY storage engines; MyISAM is unsupported
• SELECT ... INTO OUTFILE statements to write query results to files are unsupported, as the filesystem is not
directly exposed by the service
Single Server
Single Server is suitable when apps do not need extensive database customization. Single Server will manage
patching, high availability, and backups on a predetermined schedule (though developers can set the backup
retention times between a week and 35 days). To reduce compute costs, developers can pause the Single Server
offering. Single Server offers an SLA of 99.99%. For a refresher on how the SLAs of individual Azure services affect
the SLA of the total deployment, review the associated Microsoft Learn Module.
Note: Single servers are best suited for existing applications already leveraging Single Server. For all new
developments or migrations, Flexible Server is the recommended deployment option. This guide will focus
primarily on Flexible Server and will not explore Single Server in depth.
Verify that the source system meets the migration requirements listed in the Azure documentation.
02 / Summary
This module explained everyday use cases for MySQL and illustrated the typical IaaS and PaaS deployment
approaches. Additional hybrid approaches to hosting MySQL applications and databases on Microsoft Azure were
discussed. The reader was introduced to the core approaches to managing Microsoft Azure resources, including
imperative tools (like the Azure CLI and Azure PowerShell) and declarative tools (like ARM templates and
Terraform).
The emphasis of this guide will continue to be on the advantages of Azure Database for MySQL Flexible Server
versus the single server offering. Flexible Server is the preferred Azure Database for MySQL offering. This guide
will continue to reiterate the unique benefits of Flexible Server throughout the remainder of this guide and
provide references to Single Server where appropriate.
Since most Azure services are provisioned in regions, some limits apply at the regional level. Developers must
consider both global and regional subscription limits when developing and deploying applications.
Consult Azure’s comprehensive list of service and subscription limits for more details.
Azure authentication
As mentioned previously, Azure Database for MySQL consists of a data plane (data storage and data
manipulation) and a control plane (management of the Azure resource). Authentication is separated between the
control plane and the data plane as well.
In the control plane, Azure Active Directory authenticates users and determines whether users are authorized to
operate against an Azure resource. Review Azure RBAC in the Introduction to Azure resource management section
for more information.
The built-in MySQL account management system governs access for administrator and non-administrator users in
the data plane. Moreover, Single Server supports security principals in Azure Active Directory, like users and
groups, for data-plane access management. Using AAD data-plane access management allows organizations to
enforce credential policies, specify authentication modes, and more. Refer to the Microsoft docs for more
information.
Note: Flexible Server does not support Azure Active Directory principal authentication.
The MySQL extension allows developers to organize their database connections, administer databases, and query
databases. Consider adding it to Visual Studio Code environment to make working with MySQL instances more
efficient.
When you are done developing for the day, you can stop Flexible Server. This feature helps keep the
organizational costs low.
Watch: Demo: Getting Started [4 of 16] | Azure Database for MySQL - Beginners Series
Azure portal
Azure provides a Quickstart document for users who want to use the Azure portal to provision Flexible Server.
While this is a great opportunity to explore the configuration parameters of Flexible Server, IaC approaches, like
the imperative Azure CLI or the declarative ARM template, are preferable to create deployments that can easily be
replicated in other environments.
Azure CLI
The Azure CLI az mysql flexible-server set of commands is very robust. Azure’s quickstart guide demonstrates how
the az mysql flexible-server create and az mysql flexible-server db create commands can automatically populate
server parameters.
Note: It is possible to exercise greater control over these commands by reviewing the documentation for
the flexible-server create and flexible-server db create commands.
Running the CLI commands from Azure Cloud Shell is preferable, as the context is already authenticated with
Azure.
The image below, from a successful CLI provisioning attempt for Flexible Server, maps CLI flags to various Flexible
Server parameters.
ARM template
Azure provides a Quickstart document with a comprehensive ARM template for a Flexible Server deployment. We
have also provided a straightforward basic template. The Azure sample template requires additional parameters to
run. It can be deployed with the New-AzResourceGroupDeployment PowerShell command in the Quickstart or the
az deployment group create CLI command.
Connect and query Azure Database for MySQL using MySQL Workbench
This section explains how to perform queries against Azure Database for MySQL Flexible Server using MySQL
Workbench, a UI-based management tool.
Setup
Follow one of the methods in the Create a Flexible Server database document to create a Flexible Server instance
with a database.
Instructions
Explore the Use MySQL Workbench with Azure Database for MySQL Flexible Server article to perform the
following activities:
Add the SSL CA file on the SSL tab of the Setup New Connection dialog box.
Connect and query Azure Database for MySQL using the Azure CLI
Workbench is not the only method of running queries against your MySQL database. This section explains how to
perform queries against Azure Database for MySQL Flexible Server using the Azure CLI and the az mysql flexible-
server utilities and references the steps in the Quickstart: Connect and query with Azure CLI with Azure Database
for MySQL - Flexible Server article.
Setup
While the Azure article demonstrates how to provision a Flexible Server instance using the CLI, any of the
presented provisioning methods in the Create a Flexible Server database section are possible.
Instructions
The Azure CLI supports running queries interactively via the az mysql flexible-server connect command, which is
similar to running queries interactively against a MySQL instance through the MySQL CLI. It is also possible to run
an individual SQL query or a SQL file using the az mysql flexible-server execute command.
In addition to the queries in the document, it is also possible to run basic admin queries. The statements below
create a new user analyst that can read data from all tables in newdatabase.
USE newdatabase;
CREATE USER 'analyst'@'%' IDENTIFIED BY '[SECURE PASSWORD]';
GRANT SELECT ON newdatabase.* TO 'analyst'@'%';
FLUSH PRIVILEGES;
The new analyst user can also connect to newdatabase in the Flexible Server instance. The new user can only
query tables in newdatabase.
This image demonstrates running queries against the Flexible Server instance using the Azure CLI.
For more details on creating databases and users in Single Server and Flexible Server, consult this document. Note
that it uses the mysql CLI.
Language support
Once an editor is selected, the next step is to pick a development language or platform. Below are some quick
links:
PHP
Java
PHP
This section describes tools to interact with Azure Database for MySQL (Single Server and Flexible Server) through
PHP.
Moreover, install PHP from the downloads page. These instructions were tested with PHP 8.0.13 (any PHP 8.0
version should work).
The php.ini file needs to uncomment the extension=mysqli and extension=openssl lines for these steps to work.
Lastly, download the connection certificate used for SSL connections with the MySQL Flexible Server instance. In
these snippets, the certificate is saved to C:\Tools on Windows. Adjust this if necessary.
Instructions
Microsoft’s Quickstart guide performs standard CRUD operations against the MySQL instance from a console app.
This document modifies the code segments from the guide to provide an encrypted connection to the Flexible
Server instance.
The first code snippet creates a table called Products with four columns, including a primary key. Adjust the host,
username (most likely sqlroot), password, and db_name (most likely newdatabase) parameters to the values used
during provisioning. Moreover, adjust the certificate path in the mysqli_ssl_set() method.
<?php
$host = '[SERVER NAME].mysql.database.azure.com';
$username = 'sqlroot';
$password = '[PASSWORD]';
$db_name = 'newdatabase';
The second code snippet uses the same logic to start and close an SSL-secured connection. This time, it leverages
a prepared insert statement with bound parameters.
<?php
$host = '[SERVER NAME].mysql.database.azure.com';
$username = 'sqlroot';
$password = '[PASSWORD]';
$db_name = 'newdatabase';
The third code snippet utilizes the mysqli_query() method, just like the first code snippet. However, it also utilizes
the mysqli_fetch_assoc() method to parse the result set.
<?php
$host = '[SERVER NAME].mysql.database.azure.com';
$username = 'sqlroot';
$password = '[PASSWORD]';
$db_name = 'newdatabase';
PHP returns an array with the column values for the row inserted in the previous snippet.
The next snippet uses a prepared update statement with bound parameters. It modifies the Price column of the
record.
<?php
$host = '[SERVER NAME].mysql.database.azure.com';
$username = 'sqlroot';
$password = '[PASSWORD]';
$db_name = 'newdatabase';
After executing these commands, the message Update: Affected 1 rows should be displayed.
The final code snippet deletes a row from the table using the ProductName column value. It again uses a prepared
statement with bound parameters.
<?php
$host = '[SERVER NAME].mysql.database.azure.com';
$username = 'sqlroot';
$password = '[PASSWORD]';
$db_name = 'newdatabase';
Congratulations. An SSL-secured connection with Flexible Server was demonstrated, a table was created (DDL),
and some CRUD operations were performed against that table (DML).
Application connectors
There are two major APIs to interact with MySQL in PHP:
• MySQLi, MySQLi is an improvement over the earlier MySQL API, which does not meet the security needs of
modern applications.
• PDO, or PHP Data Objects, allows applications to access databases in PHP through abstractions,
standardizing data access for different databases. PDO works with a database-specific driver, like
PDO_MYSQL.
Tip: MySQLi and PDO are wrappers over the mysqlnd or libmysqlclient C libraries: it is highly recommended
to use mysqlnd as the default backend library due to its more advanced features. mysqlnd is the default backend
provided with PHP.
Flexible Server and Single Server are compatible with all PHP client utilities for MySQL Community Edition.
Resources
1. Create a PHP web app in Azure App Service
3. Introduction to PDO
4. PDO_MYSQL Reference
6. The php.ini directives allow for the customization of the PHP environment.
Java
This section describes tools to interact with Azure Database for MySQL Flexible Server through Java.
Application connectors
MySQL Connector/J is a JDBC-compatible API that natively implements the MySQL protocol in Java, rather than
utilizing client libraries. The Connect and Query sample does not directly utilize MySQL Connector/J, but Microsoft
provides a sample that uses this technology.
Developers use persistence frameworks like Spring Data JPA to accelerate development. They can focus on the
application business logic, not basic database communication. Spring Data JPA extends the JPA specification,
which governs object-relational mapping (ORM) technologies in Java. It functions on top of JPA implementations,
Flexible Server is compatible with all Java client utilities for MySQL Community Edition. However, Microsoft has
only validated MySQL Connector/J for use with Single Server due to its network connectivity setup. Refer to the
MySQL drivers and management tools compatible with Azure Database for MySQL article for more information
about drivers compatible with Single Server.
Resources
1. MySQL Connector/J Introduction
– Flexible Server
– Single Server
4. Hibernate ORM
Tooling
IntelliJ IDEA
Currently, Single Server is supported.
Eclipse
Eclipse is another popular IDE for Java development. It supports extensions for enterprise Java development,
including powerful utilities for Spring applications. Moreover, through the Azure Toolkit for Eclipse, developers
can quickly deploy their applications to Azure directly from Eclipse.
Tool-Specific Resources
2. Create a Hello World web app for Azure App Service using Eclipse
Maven
Maven improves the productivity of Java developers by managing builds, dependencies, releases, documentation,
and more. Maven projects are created from archetypes. Microsoft provides the Maven Plugins for Azure to help
Java developers work with Azure Functions, Azure App Service, and Azure Spring Cloud from their Maven
workflows.
Note: Application patterns with Azure Functions, Azure App Service, and Azure Spring Cloud are addressed
in the 04 / End to End application development story.
Tool-Specific Resources
2. Maven Introduction
Python
This section describes tools to interact with Azure Database for MySQL (Single Server and Flexible Server) through
Python.
Follow one of the methods in the Create a Flexible Server database document to create a Flexible Server instance
with a database.
Moreover, install Python 3.7 or above from the Downloads page. This sample was tested using Python 3.8.
Though a Python Virtual Environment is unnecessary for the sample to run, using one will avoid conflicts with
packages installed globally on the development system. The commands below will create a Virtual Environment
called venv and activate it on Windows. Instructions will differ for other OS.
Instructions
This section is based on Microsoft’s sample.
The first code snippet creates a table, inventory, with three columns. It uses raw queries to create the inventory
table and insert three rows. If the snippet succeeds, the following output will be displayed.
Connection established
Finished dropping table (if existed).
Finished creating table.
Inserted 1 row(s) of data.
Inserted 1 row(s) of data.
Inserted 1 row(s) of data.
Done.
Note: The sample establishes an SSL connection with the MySQL instance. Use the statement below (placed
before cursor and conn are closed) to validate the use of SSL.
config = {
'host':'[SERVER].mysql.database.azure.com',
'user':'sqlroot',
'password':'[PASSWORD]',
'database':'newdatabase',
'ssl_ca': 'C:\Tools\DigiCertGlobalRootCA.crt.pem'
}
The second code snippet connects to the MySQL instance and executes a raw query to SELECT all rows from the
inventory table. This time, it uses the fetchall() method to parse the result set into a Python iterable. An output like
the one below should display:
Connection established
Read 3 row(s) of data.
Data row = (1, banana, 150)
Data row = (2, orange, 154)
Data row = (3, apple, 100)
Done.
The third code snippet executes an UPDATE statement to change the quantity value of the record identified by
name. An output like the one below should display:
Connection established
Updated 1 row(s) of data.
Done.
The final snippet executes a raw DELETE statement against the inventory table targeting records identified by
name. An output like the one below should display:
Connection established
Deleted 1 row(s) of data.
Done.
At this point, a successfully opened connection to Flexible Server was established, a table was created (DDL), and
CRUD operations were performed (DML) against data in the table.
If a Python Virtual Environment was created, simply enter deactivate into the console to remove it. .
Application connectors
MySQL Connector/Python offers a Python Database API specification-compatible driver for MySQL database
access (PEP 249). It does not depend on a MySQL client library. The Python Connect and Query sample utilizes
MySQL Connector/Python.
Flexible Server is compatible with all Python client utilities for MySQL Community Edition. However, Microsoft has
only validated MySQL Connector/Python and PyMySQL for use with Single Server due to its network connectivity
setup. Refer to this document for more information about drivers compatible with Single Server.
Resources
1. Introduction to MySQL Connector/Python
2. PyMySQL Samples
.NET
.NET applications typically use ORMs to access databases and improve portability: two of the most popular ORMs
are Entity Framework (Core) and Dapper.
Using MySQL with Entity Framework (Core) requires MySQL Connector/NET, which is compatible with Single
Server. Learn more from the MySQL documentation about support for Entity Framework (Core).
Microsoft has also validated that MySQL Single Server is compatible with the Async MySQL Connector for .NET.
This connector works with both Dapper and Entity Framework (Core).
Ruby
The Mysql2 library, compatible with Single Server, provides MySQL connectivity in Ruby by referencing C
implementations of the MySQL connector.
03 / Summary
This module augmented an understanding of Flexible Server through practical examples of how modern
applications access Flexible Server. Flexible Server, unlike Single Server, supports all standard MySQL clients.
Previously presented information Microsoft Azure deployment tools and concepts were utilized to provision a
Flexible Server instance to run the included code examples.
In the next section, the Contoso NoshNow Sample Application provides a starting point for the entire developer
journey. It provides high-level concepts and shows how MySQL apps can evolve into a scalable modern
applications.
With a configured development environment available, it is time to explore the various architecture and
deployment options available when deploying an application and its corresponding MySQL database.
This image shows a Data Exposed video explaining the benefits that Flexible Server offers for application
development.
Watch: Develop applications faster with Azure Database for MySQL – Flexible Server | Data Exposed
Web Apps
Developers can deploy MySQL-backed apps to Azure on a Windows or Linux environment through Azure App
Service, a PaaS platform that supports popular frameworks, including PHP, Java, Python, Docker containers, and
more. App Service is compatible with manual deployment mechanisms, including ZIP files, FTP, and local Git
Resources
• App Service overview
Serverless Compute
Azure Functions and Azure Logic Apps are serverless platforms, meaning that customers are billed only for the
execution time of their code. Azure automatically scales compute resources up and down in response to demand.
Azure Functions
An Azure Functions instance consists of individual functions that execute in response to a trigger, like a cron job or
an HTTP request. These functions interface with other Azure resources, like Cosmos DB, through bindings, though
resources without default bindings, like Azure Database for MySQL, can be accessed through language-specific
connectors.
Like Azure App Service, Function Apps support multiple programming languages. Developers can extend support
to unsupported languages through custom handlers.
For long-running, stateful serverless architectures, such as when human intervention is necessary, Azure provides
the Durable Functions extension. Consult the documentation for more information about architectures with
Durable Functions.
Resources
• Introduction to Azure Functions
Azure Logic Apps interface with external systems through managed connectors. Microsoft provides a managed
connector for MySQL databases, but this connector cannot easily be used for Azure Database for MySQL, as the
MySQL managed connector accesses local MySQL databases through a data gateway.
Resources
• What is a Azure Logic App?
Microservices
Organizations deploy microservices architectures to offer resilient, scalable, developer-friendly applications. Unlike
traditional monolithic apps, each service operates independently and can be updated without redeploying the
app. Each service also manages its persistence layer, meaning that service teams can perform database schema
updates without affecting other services.
While microservices apps offer major benefits, they require advanced tools and knowledge of distributed systems.
Organizations utilize domain analysis to define optimal boundaries between services.
On Azure, organizations often deploy microservices to Azure Kubernetes Service through CI/CD platforms, such as
GitHub Actions.
Resources
• Build microservices on Azure
API Management
Azure API Management allows organizations to manage and securely expose their APIs hosted in diverse
environments from a central service. API Management simplifies legacy API modernization, API exposure to
multiple platforms, and data interchange between businesses. Applications call APIs through an API gateway that
validates credentials, enforces quotas, serializes requests in different protocols, and more. Developers operate
their API Management instances through the management plane, and they expose API documentation for internal
and external users through the Developer portal.
Like other Azure resources, API Management offers comprehensive RBAC support, accommodating internal
administrative and development staff and external users. Moreover, as API Management integrates with APIs
hosted in environments outside Azure, organizations can self-host the API gateway while retaining the Azure
management plane APIs.
Resources
• About API Management
Event-driven - Azure Event Grid vs. Service Bus vs. Event Hubs
Event-driven apps create, ingest, and process events (state changes) in real-time. Event producers and event
consumers are loosely-coupled, and every consumer sees every event. Event-driven architectures can perform
complex event handling, such as aggregations over time, and operate with large volumes of data produced
rapidly.
Example Solution
An e-commerce site can use Service Bus to process an order, Event Hubs to capture site telemetry, and Event Grid
to respond to events like an item was shipped.
Cron jobs
Developers use cron jobs to run operations on a schedule. They are often useful for administrative tasks, like
taking site backups. Azure Functions and Logic Apps support cron jobs:
• Azure Functions: The timer trigger executes a function on a schedule. Azure Functions supports more
complex scheduling tasks, like specifying the cron job time precision.
• Logic Apps: Logic Apps supports Recurrence triggers and Sliding Window triggers. Recurrence triggers
run Logic Apps on a schedule, while Sliding Window triggers extend Recurrence triggers by executing
occurrences that were missed (e.g. the Logic App was disabled).
WebJobs
Azure WebJobs, like Azure Functions, process events in Azure services. WebJobs executes code in an App Service
instance, and it works best with the WebJobs SDK. However, WebJobs with the WebJobs SDK only supports C#.
Azure Functions is built on the WebJobs SDK. It offers more developer flexibility than WebJobs and serverless
execution. However, WebJobs provides more control over how events are received than what Azure Functions
exposes.
Azure Data Factory supports Azure PaaS and generic (on-premises) MySQL instances.
The development team knew migrating to Azure could help with these issues.
Solution architecture
This is the base application that will evolve in the future sample scripts. This PaaS architecture is a couple of steps
ahead of the Classic architecture. The Classic architecture is meant to be an example of an existing on-premises
environment that might be migrated to the Azure cloud. If you have a new application, you most likely will start
with the PaaS architecture depicted below. This is the easiest path for a user looking to understand the Azure
basics.
This image shows a sample architecture involving a PHP App Service instance and a Flexible Server instance.
Site map
The web application is simple, but covers the fundamentals.
The following scenarios will be discussed and demonstrated as part of this Azure MySQL developer’s guide. All of
the following deployments will utilize the same application and database backend and what is needed to modify
the application to support the targets. Topics will be discussed in the following simple to complex architecture
order.
2. Azure VM Deployment
3. Simple App Service deployment with Azure Database for MySQL Flexible Server
Classic deployment
In a classic deployment, development and operations staff will typically set up a web server (such as Internet
Information Services (IIS), Apache, or NGINX) on physical or virtualized on-premises hardware. Most applications
using MySQL as the backend are using PHP as the frontend (which is the case for the sample application in this
guide); as such, the web server must be configured to support PHP. This includes configuring and enabling any
PHP extensions and installing the required software to support those extensions.
Some web servers are relatively easier to set up than others. The complexity depends on what the target
operating system is and what features the application and database are using, for example, SSL/TLS.
In addition to the web server, it is also necessary to install and configure the physical MySQL database server. This
includes creating the schema and the application users that will be used to access the target database(s).
As part of our sample application and supporting Azure Landing zone created by the ARM templates, most of this
gets set up automatically. Once the software is installed and configured, it is up to the developer to deploy the
application and database on the system. Classical deployments tend to be manual such that the files are copied to
the target production web server and then deploy the database schema and supported data via MySQL tools or
the MySQL Workbench.
The biggest advantage of a classic on-premises deployment is the infrastructure team will have full control of the
environment. The biggest weakness is they must also maintain every aspect of the environment as well.
To perform a simulated classical deployment in Azure, go to the Classic Deployment to PHP-enabled IIS server
article.
The advantages of using Azure to host virtual machines include the ability to enable backup and restore services,
disk encryption, and scaling options that require no upfront costs and provide flexibility in configuration options
with just a few clicks of the mouse. This is in contrast to the relatively complex and extra work needed to enable
these types of services on-premises.
Simple App Service deployment with Azure Database for MySQL Flexible
Server
If supporting the operating system and the various other software is not a preferred approach, the next
evolutionary path is to remove the operating system and web server from the list of setup and configuration
steps. This can be accomplished by utilizing the Platform as a Service (PaaS) offerings of Azure App Service and
Azure Database for MySQL.
However, modernizing an application and migrating them to these aforementioned services may introduce some
relatively small application changes.
Administration and integration are accomplished through a built-in myphpadmin interface in the Azure Portal.
From this admin portal, it is possible to run any supported SQL commands to import or export the database.
The limits of the MySQL instance are primarily driven by the size of the corresponding App Service Plan. The
biggest factor about limits is normally the disk space allocated to any App Services in the Plan. App Service Plan
storage sizes range from 1GB to 1TB; therefore, if a database will grow past 1TB, it cannot be hosted as InApp and
it will need to be hosted in Flexible Server. For a list of other limitations, reference Announcing Azure App Service
MySQL in-app.
To implement this deployment, reference the Cloud Deployment to Azure App Service with MySQL InApp article.
Whether using Azure DevOps or Github, there will be some setup work to support the deployments. This typically
includes creating credentials that can connect to the target environment and deploy the release artifacts.
To perform deployments using Azure DevOps and GitHub Actions, reference the Deployment via CI/CD article.
Containers solve the potential issue of misconfiguration of the target environment. By containerizing the
application and data, the application will run as intended. Containers can also more easily be scaled using tools
such as Kubernetes.
Containerizing an application and data layer can be relatively complex, but once the build environment is set up
and working, it is possible to push container updates very quickly to multi-region load-balanced environments.
To perform deployments using Docker, reference the Migrate to Docker Containers article. This article
containerizes the Laravel sample application and its MySQL database as separate containers that communicate
through the Docker runtime on the VM instance.
Azure Container Instances can deploy one container at a time or multiple containers to keep the application, API,
and data contained in the same resource.
To implement this deployment, reference the Migrate to Azure Container Instances (ACI) article. This article serves
the Laravel app and MySQL database containers on ACI. It also utilizes an Azure File Share to persist data.
To perform deployments using Azure App Service containers, reference the Migrate to Azure App Service
Containers article. This example deploys both the database and web app containers to App Service for Containers.
• In supported regions, co-locating Flexible Server and AKS nodes in the same availability zone minimizes
latency.
• Applications can host database proxies, like ProxySQL for MySQL, on the same infrastructure as their apps.
• Teams can manage Flexible Server instances directly from AKS through the Azure Service Operator.
To perform deployments using AKS, reference the Migrate to Azure Kubernetes Services (AKS) article to host the
database and web app containers on an enterprise-ready AKS instance.
To implement this deployment, reference the Utilize AKS and Azure Database for MySQL Flexible Server article.
This article extends the benefits of a PaaS database to the Contoso NoshNow application.
We provided two ARM templates that can be deployed that will set up the environment. The template is a
JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. In the
template, you specify the resources to deploy and the properties for those resources.
One is a basic deployment of services that are exposed to the Internet and the other is a more secure
environment that utilizes private endpoints and VNet integrations. It also includes items like Azure Firewall and
other security-related configurations.
The basic template is the cheaper way to go and should work without any configuration. The secure template will
have much higher costs and requires special configuration to get the samples to work properly.
Azure Portal
This image shows the Build your own template in the editor button.
This image shows how to load the ARM template from the local drive.
• Check for validation errors. For example, you may have exceeded your quota for that subscription and
region.
Another option for deploying infrastructure using a template is to use Azure CLI or PowerShell. Here is a tutorial
guide:
Step 1 - Build the development environment - deploy one of the templates below
This is an optional step if you have your development environment already set up. You will need to install the
basic Azure development packages.
• Basic Template
• Secure Template
• Select Connect->RDP
Once in the virtual machine, notice that all the necessary development tools have been installed. Additionally, the
supporting GitHub repository has been downloaded that includes all the artifacts needed to start the developer
journey. These files can be found on the mysqldevSUFFIX-paw1 machine in the C:\labfiles\microsoft-mysql-
developer-guide folder.
1. Classic deployment
2. Azure VM Deployment
3. Simple App Service Deployment with Azure Database for MySQL Flexible Server
• Azure Functions
– Dotnet
– Python
– AKS
• Logic Apps
• Azure Batch
After reviewing the need for microservice architecture and the typical design patterns, you can see how the
Sample Application architecture changed when it utilizes a Java REST microservice architecture.
• Continuous Integration (CI): CI tools automatically build, test, and merge code that developers push to
version control systems. CI pipelines run code analysis tools to enforce style guidelines, unit tests,
integration tests, and more. By constantly merging developers’ contributions to a shared branch, CI tools
improve developer efficiency.
• Continuous Delivery (CD): Continuous delivery tools package applications in a format that operations
teams can deploy to production. This typically involves pushing a container image to a container registry.
• Continuous Deployment (CD): Continuous deployment automates the production deployment process;
it does not require an operations team to intervene. Continuous deployment processes extend continuous
delivery.
CI/CD tools
Below are some common CI/CD tool options.
Jenkins
There are a plethora of CI/CD tools available for local Git repositories, such as Jenkins. Jenkins is an open-source
project that supports over 1,500 extensions and offers advanced features, such as parallel test execution.
Local Git
Azure App Service supports automated deployments from local Git repositories: developers simply need to push
their code to an App Service remote repository. Consult the Running the sample application for a step-by-step
App Service deployment from a local Git repository.
GitHub Actions
GitHub Actions runs automated pipelines after an event occurs, such as when a developer pushes to a repository
branch or opens a PR. As GitHub Actions integrates with GitHub repositories, pipelines can respond to other
repository events, such as when a new issue is opened.
A GitHub repository can have multiple workflows (pipelines) written in YAML. At their most basic level, workflows
consist of actions that perform basic tasks, such as initializing a build tool. Teams can run GitHub Actions on
GitHub runners or self-hosted runners for greater flexibility.
Azure DevOps
Azure DevOps includes multiple tools to improve team collaboration and automate building, testing, and
deploying apps.
• Azure Boards: Azure Boards helps teams plan and track work items. It supports multiple processes.
• Azure Pipelines: Azure Pipelines is Microsoft’s CI/CD pipeline platform. It supports deployment to PaaS
services, virtual machines, and container registries in Azure, other cloud platforms, and on-premises. Azure
Pipelines integrates with common version control systems, like GitHub, GitLab, and Azure Repos.
• Azure Test Plans: Azure Test Plans allows development teams to create manual tests, for feedback from
developers and stakeholders, and automated tests, which are necessary for any CI/CD pipeline.
• Azure Artifacts: Azure Artifacts allows organizations to share packages, such as NuGet and npm packages,
internally and publicly. Azure Artifacts integrates with Azure Pipelines.
Organizations can quickly start exploring Azure DevOps by creating a free organization. Azure DevOps’ suite of
project management, CI/CD, and testing tools empowers organizations to deploy more frequently, more quickly,
and with fewer failures.
Both Azure Pipelines and GitHub Actions support automated ARM template deployments. Moreover, through the
Azure Service Operator, development teams can provision Azure resources from Kubernetes, integrating
infrastructure management into existing Kubernetes release pipelines. Here is a Microsoft sample provisioning
Flexible Server from Kubernetes.
04 / Summary
This module was designed to bring all the elements of the modernization and cloud adoption journey together via
a progressive set of examples and learning paths. After completing all of the samples in this module, a developer
will understand where an application sits in the modernization process and how to take it to the next level via
containers and container hosting environments.
Although this guide did not go into detail about how to host applications across multiple cloud providers, this
would be the next logical step in the evolution of MySQL applications and databases. Several Microsoft partners
and vendors (such as Hashicorp) provide tools and services that help facilitate this final step.
As the world of microservices continues to change and evolve through more innovative technologies (such as
blockchain, other patterns and steps may emerge in the future that will change the evolutionary course of your
architecture(s).
By using containers, developers can be assured the code will run consistently for specific target environments.
However, when multiple containers are involved or are moved from one environment to another (such as AKS to
Azure Service Fabric or some other container cloud provider), resources may not run well or at all. The
management plane may not be configured properly to support the containers. Following the approaches defined
in this section will help developers understand the tools available and what they should be looking for when
designing microservices.
Checklist
• Understand the basic Azure fundamental services.
• Be cognizant of the changes that are needed for applications to move to the next state.
Overview
Proper monitoring management helps with the following:
Azure can monitor these types of operational activities using tools such as Azure Monitor, Log Analytics, and
Azure Sentinel. In addition to the Azure-based tools, external security information and event management (SIEM)
systems can be configured to consume these logs as well.
Alerts should be created to warn administrators of outages, operational performance problems, or suspicious
activities. If a particular alert event has a well-defined remediation path, alerts can automatically fire Azure
runbooks to address and resolve the event.
• Application monitoring
• Database monitoring
This image clarifies how Azure Monitor integrates with various Azure data sources and management tools.
For more information on what can be monitored, read: What is monitored by Azure Monitor?
The Activity log is a platform log in Azure that provides insight into subscription-level events. The Activity log
includes information like when a resource is modified or when a virtual machine was started.
Event examples:
Log Analytics is a tool in the Azure portal used to edit and run log queries with data in Azure Monitor Logs. You
can use Log Analytics queries to retrieve records that match particular criteria. Use the query results to identify
trends, analyze patterns, and provide insights. Users can create charts to visualize important data in the portal.
Query examples:
Workbooks provide a flexible canvas for data analysis and the creation of rich visual reports within the Azure
portal. They allow you to tap into multiple Azure data sources and combine them into unified interactive
experiences. Visualize data in one interactive report.
Azure Resource Health helps you diagnose and get support for service problems that affect your Azure resources.
It reports on the current and past health of your resources. Resource Health can help you diagnose the root event
causes.
Multiple Azure infrastructure components can trigger Platform events. The events include scheduled actions
(planned maintenance) and unexpected incidents (unplanned host reboot or degraded hosted hardware that is
predicted to fail after a specified time window).
Resource Health provides additional details about the event and the recovery process. It also enables you to
contact Microsoft Support, even if you don’t have an active support agreement.
• Events triggered by user actions, for example a user rebooting a virtual machine
Application monitoring
It is important to monitor the uptime, performance, and understand usage patterns once an application has been
deployed. Application Insights is a feature that provides extensible application performance management (APM)
and monitoring for web-based applications.
The instrumentation code directs telemetry data to an Application Insights resource by using a unique
instrumentation key and URL.
• Then go to Settings and Application Insights inside WordPress, and add the key there.
For example, to capture performance counters for a PHP App Service resource, simply follow these steps.
• Determine your scope. Navigate to the App Service in the Azure Portal.
The picture shows the time frame options for metric filtering.
Customers with larger volumes of telemetry are charged by the gigabyte. These environments should be
monitored closely to ensure your finance department does not get a larger than expected Azure invoice. Manage
usage and costs for Application Insights
Metrics
For more specific metrics, navigate to the Monitoring section. Select Metrics. More custom granular metrics can
be configured and displayed.
Monitor Azure Database for MySQL Flexible Servers with built-in metrics
Diagnostic settings
Diagnostic settings allow you to route platform logs and metrics continuously to other storage and ingestion
endpoints.
This image shows how to graph metrics in the Azure portal Monitoring tab.
Set up diagnostics
Log Analytics
Once you configure your Diagnostic Settings, you can navigate to the Log Analytics workspace. You can perform
specific filtered queries on interesting categories. Are you looking for slow queries?
Now, you can review the results from your query. There is a wealth of information about the category.
This image shows a KQL query that polls the MySQL audit log.
Workbooks
As mentioned previously, Workbooks is a simple canvas to visualize data from different sources, like Log Analytics
workspace. It is possible to view performance and storage metrics all in a single pane.
CPU, IOPS, and other common monitoring metrics are available. You can also access Query Performance Insight.
In addition to the fundamental server monitoring aspects, Azure provides tools to monitor application query
performance. Correcting or improving queries can lead to significant increases in the query throughput. Use the
Query Performance Insight tool to:
• Analyze the longest-running queries and determine if it is possible to cache those items.
• If they are deterministic within a set period, modify the queries to increase their performance.
In addition to the query performance insight tool, Wait statistics provides a view of the wait events that occur
during the execution of a specific query.
Warning: Wait statistics are meant for troubleshooting query performance issues. It is recommended to be
turned on only for troubleshooting purposes.
Finally, the slow_query_log can be set to show slow queries in the MySQL log files (default is OFF). The
long_query_time server parameter can be used to log long-running queries (default long query time is 10 sec).
Monitor Azure Database for MySQL Flexible Server by using Azure Monitor workbooks
Activity logs
This area captures the administrative events captured over a period of time.
The event details can be viewed as well. These details can be extremely helpful when troubleshooting.
Creating alerts
You can create alerts in a couple of ways. Navigate to the Alerts menu item in the portal and create it manually.
This image shows how to create resource alerts in the Azure portal.
This image shows how to create resource alerts from the Metrics section in the Azure portal.
Once the alert has been configured, you can create an action group to send a notification to the operations team.
Server Logs
Server logs from Azure Database for MySQL can also be extracted through the Azure platform resource logs, which
track data plane events. Azure can route these logs to Log Analytics workspaces for manipulation and visualization
through KQL.
In addition to Log Analytics, the data can also be routed to Event Hubs for third-party integrations and Azure
storage for long-term backup.
In addition to metrics, it is also possible to enable MySQL logs to be ingested into Azure Monitor. While metrics
are better suited for real-time decision-making, logs are also useful for deriving insights. One source of logs
generated by Flexible Server is MySQL audit logs, which indicate connections, DDL and DML operations, and more.
Many businesses utilize audit logs to meet compliance requirements, but they can impact performance.
Warning: Excessive audit logging can degrade server performance, so be mindful of the events and users
configured for logging.
For more details about the logging server parameters, including the type of events that can be logged, consult the
documentation.
Alerting guidelines
Once monitoring data is configured to flow into Azure Monitor or Log Analytics, the next step would to be to
create alerts when issue data is generated. The operations team will want to know as quickly as possible when a
pending outage or system issue is developing. Understanding the symptoms is critical. “You can’t fix what you
don’t know is broken.”
Alert creation and remediation will take fine-tuning to ensure that alert fatigue does not set in. Focus less on
integrating monitoring with IT Service Management (ITSM) systems for Incident Management, and seize on
opportunities to let cloud automation replace more expensive service management processes, thereby eliminating
time spent on easily automatically resolvable alerts and incidents.
Consider the following principles for determining whether a symptom is an appropriate candidate for
alerting:
• Does it matter? Is the issue symptomatic of a real problem or issue influencing the overall health of the
application? For example, does it matter whether the CPU utilization is high on the resource? Or that a
particular SQL query running on a SQL database instance on that resource is consuming high CPU
utilization over a sustained period? If the CPU utilization condition is a real issue, alerts should be fired
when it occurs. Although an alert will fire, the team will still need to determine what is causing the alert
condition in the first place. Alerting and notifying on the SQL query process utilization issue is both
relevant and actionable.
• Is it urgent? Is the issue real, and does it need urgent attention? If so, the responsible team should be
immediately notified.
• Are your customers affected? Are users of the service or application affected as a result of the issue?
Test and validate the assumptions in a nonproduction environment, and then deploy them into production.
Monitoring configurations are derived from known failure modes, test results of simulated failures, and
experiences from different members of the team.
Metric alerts
Metric alerts assess metric time-series according to defined conditions and take action. They consist of the
following parts:
• Alert rules define the alert conditions. They require the following information:
– A polling frequency to determine if the previous conditions are met (e.g. 5 minutes)
• Action groups define notification actions, such as emailing or texting an administrator, and other actions
to take, like calling a webhook or Azure Automation Runbooks
• Alert processing rules is a preview feature that filters alerts as they are generated to modify the actions
taken in response to that alert (i.e. by disabling action groups)
Refer to Microsoft’s tutorial explaining the configuration of a metric alert for a Flexible Server instance.
• If there were 10 or more failed connections (total of aborted_connections in Flexible Server) in the last 30
minutes, then send an email alert
• If IOPS is 90% or more of capacity (average of io_consumption_percent in Flexible Server) for at least 1
hour, then call a webhook
Webhooks
Webhook action groups send POST requests to configured webhook endpoints. Action groups can use the
common alert schema for webhook calls, or custom JSON payloads. This feature allows Azure Monitor to integrate
with incident management systems like PagerDuty, call Logic Apps, and execute Azure Automation runbooks.
Metrics resources
Azure CLI
Azure CLI provides the az monitor series of commands to manipulate action groups (az monitor action-group),
alert rules and metrics (az monitor metrics), and more.
• Monitor and scale an Azure Database for MySQL Flexible Server using Azure CLI
Azure Portal
While the Azure Portal does not provide automation capabilities like the CLI or the REST API, it does support
configurable dashboards and provides a strong introduction to monitoring metrics in MySQL.
To interact with the REST API, applications first need to obtain an authentication token from Azure Active
Directory and then use that token in API requests.
05 / Summary
Monitoring the performance of your environment is a vital final step after deployment. This section described how
Azure Monitor and Log Analytics are essential tools to assist in monitoring your applications.
Both the control and data plane should be considered in your monitoring activities. Platform administrators and
database administrators should be notified of issues before or when they start to happen.
Checklist
• Define a monitoring strategy to provide useful insights without deteriorating application performance and
incurring excessive costs. For example, storing slow query logs on Flexible Server instances without proper
management consumes storage space, affects database performance.
• Configure your Azure resources to emit strategic logs (like MySQL Flexible Server slow query logs) and
route them to Azure destinations, like Log Analytics workspaces.
• Develop KQL queries to record database performance, query performance, and DDL/DML activity.
• If necessary, configure alert rules for metrics and logs. Azure can automatically respond to fired alerts
through Azure Automation runbooks.
Recommended content
• Best practices for alerting on metrics with Azure Database for MySQL monitoring
• Write your first query with Kusto Query Language (Microsoft Learn)
• Configure and access audit logs for Azure Database for MySQL in the Azure Portal
• Monitor Azure Database for MySQL using Percona Monitoring and Management (PMM)
Azure Database for MySQL provides several mechanisms to secure the networking layers by limiting access to only
authorized users, applications, and devices.
Watch: Networking and Security [6 of 16] | Azure Database for MySQL - Beginners Series
Public Access
By default, Azure Database for MySQL allows access to Internet-based clients, including other Azure services. If
this is an undesirable state, firewall access control lists (ACLs) can limit access to hosts that fall within the allowed
trusted IP address ranges.
The first line of defense for protecting a MySQL instance access is to implement firewall rules. IP addresses can be
limited to only valid locations when accessing the instance via internal or external IPs. If a MySQL instance’s
purpose is to serve internal applications, then restrict public access.
Firewall rules are set at the server level, meaning that they govern network access to all databases on the server
instance. While it is best practice to create rules that allow specific IP addresses or ranges to access the instance,
developers can also enable network access from all Azure resources. This feature is useful for Azure services
without fixed public IP addresses, such as Azure Functions that use public networks to access the server and
databases.
Note: Restricting access to Azure public IP addresses still provides network access to the instance to public
IPs owned by other Azure customers.
• Flexible Server
– Manage firewall rules for Azure Database for MySQL - Flexible Server using the Azure portal
– Manage firewall rules for Azure Database for MySQL - Flexible Server using Azure CLI
• Single Server
– Create and manage Azure Database for MySQL firewall rules by using the Azure CLI
Private Access
As mentioned, Azure Database for MySQL supports public connectivity by default. However, most organizations
will utilize private connectivity to limit access to Azure virtual networks and resources.
Note: There are many other basic Azure Networking considerations that must be taken into account that
are not the focus of this guide.
Warning: The allocation blocks of the virtual networks cannot overlap. It is best practice to choose
allocation blocks from RFC 1918.
Note: When deploying a resource such as a VM into a virtual network, the virtual network must be located
in the same region and Azure subscription as the Azure resource. Review the Introduction to Azure document for
more information about regions and subscriptions.
Each virtual network is further segmented into subnets. Subnets improve virtual network organization and
security, just as they do on-premises.
When moving an application to Azure along with the MySQL workload, there will likely multiple virtual networks
set up in a hub and spoke pattern that will require Virtual Network Peering to be configured. Virtual networks are
joined through peering. The peered virtual networks can reside in the same or different Azure regions.
Lastly, it is possible to access resources in a virtual network from on-premises. Some organizations opt to use VPN
connections through Azure VPN Gateway, which sends encrypted traffic over the Internet. Others opt for Azure
ExpressRoute, which establishes a private connection to Azure through a service provider.
– Portal
– PowerShell
– CLI
Flexible Server
Flexible Server supports deployment into a virtual network for secure access. When enabling virtual network
integration, the target virtual network subnet must be delegated, meaning that it can only contain Flexible Server
instances. Because Flexible Server is deployed in a subnet, it will receive a private IP address. To resolve the DNS
names of Azure Database for MySQL instances, the virtual networks are integrated with a private DNS zone to
support domain name resolution for the Flexible Server instances.
Note: If the Flexible Server client, such as a VM, is located in a peered virtual network, then the private DNS
zone created for the Flexible Server must also be integrated with the peered virtual network.
Note: Private DNS zone names must end with mysql.database.azure.com. If you are connecting to the Azure
Database for MySQL - Flexible sever with SSL and are using an option to perform full verification
(sslmode=VERIFY_IDENTITY) with certificate subject name, use .mysql.database.azure.com in your connection
string.
For more information on configuring Private Access for Flexible Server, reference the following:
• Azure Portal
• Azure CLI
For a review of availability zones, consult the Introduction to Azure Database for MySQL document.
• Organize the application components into multiple virtual networks, such as in a hub and spoke
configuration. Employ virtual network peering or VPN Gateways to join the application’s virtual networks.
• Configure data protection at rest and in motion (see the Security and Compliance document).
– Employ tools like network security groups to secure traffic within and between subnets.
Organizations must take proactive security measures to protect their workloads in today’s geopolitical
environment. Azure simplifies many of these complex tasks and requirements through the various security and
compliance resources provided out of the box. This section will focus on many of these tools.
Encryption
Azure Database for MySQL offers various encryption features, including encryption for data, backups, and
temporary files created during query execution.
Data stored in the Azure Database for MySQL instances are encrypted at rest by default. Any automated backups
are also encrypted to prevent potential leakage of data to unauthorized parties. This encryption is typically
performed with a key generated when the Azure Database for MySQL instance is created.
In addition to be encrypted at rest, data can be encrypted during transit using SSL/TLS. SSL/TLS is enabled by
default. As previously discussed, it may be necessary to modify the applications to support this change and
configure the appropriate TLS validation settings. It is possible to allow insecure connections for legacy
applications or enforce a minimum TLS version for connections, but this should be used sparingly and in highly
network-protected environments. Flexible Server’s TLS enforcement status can be set through the
require_secure_transport MySQL server parameter. Consult the guides below.
• Flexible Server
• Single Server
Microsoft Sentinel
Many of the items discussed thus far operate in their sphere of influence and are not designed to work directly
with each other. Every secure feature provided by Microsoft Azure and corresponding applications, like Azure
Active Directory, contains a piece of the security puzzle.
Disparate components require a holistic solution to provide a complete picture of the security posture and the
automated event remediation options.
Microsoft Sentinel is the security tool that provides the needed connectors to bring all your security log data into
one place and then provide a view into how an attack may have started.
Microsoft Sentinel works with Azure Log Analytics and other Microsoft security services to provide a log storage,
query, and alerting solution. Through machine learning, artificial intelligence, and user behavior analytics (UEBA),
Microsoft Sentinel provides a higher understanding of potential issues or incidents that may not have seen in a
disconnected environment.
Microsoft Purview
Data privacy has evolved into an organizational priority over the past few years. Determining where sensitive
information lives across your data estate is required in today’s privacy-centered society.
Security baselines
In addition to all the topics discussed above, the Azure Database for MySQL security baseline is a basic set of
potential tasks that can be implemented on your Azure Database for MySQL instances to further solidify your
security posture.
06 / Summary
Protecting the data and control plane is just another piece to the puzzle of having a robust, secure and
performant application environment.
Deciding what risks the organization can accept will typically help guide what security features discussed in this
section should be enabled and paid for.
If the data is vital and business critical, everything possible should be done to ensure its protected and secure.
This section discussed many tools Microsoft Azure provided to give an organization peace of mind that the cloud-
based workload will be just as secure as if running it on-premises.
Security checklist
• Utilize the most robust possible authentication mechanisms such as Azure Active Directory.
• Utilize private endpoints for workloads that do not travel over the Internet.
This chapter discusses the various types of tests you can run against Azure database for MySQL application and
database. Running tests ensures the optimal performance of your application and database deployments.
Approaches
Let’s discuss the types of approaches and tools.
Functional testing
Functional testing ensures that an app functions as documented in the user and business requirements. Testers do
not know how software systems function; they ensure systems perform the business functions specified in the
documentation. Functional tests validate things like data limits (field lengths and validation) and that specific
actions are taken in response to various triggers. The tests usually involve some type of application user interface.
It is usually the most complete type of testing for UI applications.
To get started with Selenium, developers can install the Selenium IDE to generate testing scripts from browser
interactions. The Selenium IDE is not intended for production tests. Still, it can speed up the development of your
test script development tasks.
Teams can include Selenium tests in Azure DevOps.. The screenshot below demonstrates a Selenium test running
in a DevOps Pipeline.
This image shows how to implement a Blue/Green test using Azure Traffic Manager.
Azure has the capability to support this type of testing via Deployment Center, Azure Traffic Manager, and other
tools.
Performance testing
Load testing
Load testing determines an application’s performance as load increases. Load testing tools typically simulate users
or requests, and they help companies meet their user and business SLAs. Proper load testing requires knowledge
of the load a production system normally experiences and potential Azure service limits (e.g. Event Hub
throughput by tier).
Stress testing
Stress testing determines the maximum load a system can handle before failure. A proper stress testing approach
would be to perform stress testing at different Azure service tiers and determine appropriate thresholds when
scaling within those tiers. This will give administrators an idea of how to build alerts for monitoring if the
application starts to approach these known limits. Knowing your acceptable low and high stress range levels is
necessary to minimize costs (by selecting the appropriate tier and scaling) and thereby provide a positive user
experience.
Apache JMeter
Apache JMeter is an open source tool to test that systems function and perform well under load. It can test web
applications, REST APIs, databases, and more. JMeter provides a GUI and a CLI, and it can export test results in a
variety of formats, including HTML and JSON.
The image below demonstrates one approach to operating JMeter at scale using Azure Container Instances. The
jmeter-load-test pipeline manages the test infrastructure and provides the test definition to the JMeter
Controller.
It is also possible to run JMeter load tests using Azure Load Testing Preview.
K6
Grafana K6 is a load testing tool hosted locally or in the cloud. Developers script tests using ES6 JavaScript.
Supporting over 20 integrations, including Azure DevOps Pipelines, K6 is a popular choice for many teams.
The image below demonstrates container logs from a containerized deployment of the Contoso NoshNow sample
app running in AKS. These logs are analyzed in the cluster’s Log Analytics workspace.
The image below demonstrates the cluster’s maximum CPU usage over a half-hour period. It utilizes metrics
provided by AKS, though more granular metrics from Container insights can also be used.
This image demonstrates the maximum CPU usage of the AKS cluster’s nodes, a feature provided by metrics from
AKS.
Resources
• Supported languages for Azure App Insights
Grafana is a visualization tool to create customizable dashboards from time-series databases. These visualizations
supplement the raw metrics exposed by services such as Prometheus.
The image below demonstrates two charts in Grafana demonstrating the CPU usage of a Laravel pod in the
Contoso Nosh Now AKS deployment. The requests and limits values were supplied in the Kubernetes deployment
file.
This image demonstrates a dashboard in Grafana showing CPU usage for a pod.
Recommended content
The following resources are helpful for exploring various approaches to using the previously mentioned tools and
concepts.
• Store Prometheus Metrics with Thanos, Azure Storage and Azure Kubernetes Service (AKS)
07 / Summary
Testing your applications after they have been deployed to an existing or a new environment is a vital step in the
development cycle. It could prevent unwanted downtime or lost of application functionality.
Checklist
• Perform functional testing on applications and databases.
• Utilize industry standard tools and benchmarks to ensure accurate and comparable results.
• Integrate reporting tools such as Azure Monitor, Grafana or Prometheus into your testing suites.
Before jumping into specific and time consuming performance enhancements/investigation, there are some
general tips that can improve performance in your environment that this section will explore.
• Ensure the input/output operations per second (IOPS) are sufficient for the application needs. Keep the IO
latency low.
• Create and tune the table indexes. Avoid full table scans.
• Make sure the application/clients (e.g. App Service) are physically located as close as possible to the
database. Reduce network latency.
• Use accelerated networking for the application server if you use a Azure virtual machine, Azure
Kubernetes, or App Services.
• Use connection pooling when possible. Avoid creating new connections for each application request.
ProxySQL for built-in connection pooling and load balancing. Balance your workload to multiple read
replicas as demand requires without any changes in application code.
• Consider using query caching solution like Heimdall Data Proxy. Limit connections based on per user and
per database. Protect the database from being overwhelmed by a single application or feature.
• Temporarily scale your Azure Database for MySQL resources for taxing tasks. Once your task is complete,
scale it down.
See Best practices for optimal performance of your Azure Database for MySQL
If CPU and memory do not seem to be the issue, administrators can explore database-based options such as
indexing and query modifications for poor-performing queries.
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.DBFORMYSQL"
| where Category == 'MySqlSlowLogs'
| project TimeGenerated, LogicalServerName_s, event_class_s, start_time_t , query_time_d, sql_text_s
| top 5 by query_time_d desc
You can also adjust the IOPS for better transactions per second (TPS) performance. You can use an Azure CLI
script to monitor relevant metrics and scale the server.
Do not be surprised. Set up alerts on thresholds to ensure that notifications can be sent to administrators before
servers reach limits. Based on the defined limits, check if scaling the database SKU to a higher compute size or to
a better pricing tier increases performance enough to meet the workload requirements.
Geo-restore can be used to recover from a service outage in the primary region. However, the Flexible Server
instance created in the paired region can only be configured with locally redundant storage, as its paired region
(the old primary region) is down.
Server parameters
As part of the migration, the on-premises server parameters were likely modified to support a fast egress. Also,
modifications were made to the Azure Database for MySQL Flexible Server parameters to support a fast ingress.
The Azure server parameters should be set back to their original on-premises workload-optimized values after the
migration.
However, be sure to review and make server parameter changes that are appropriate for the workload and the
environment. Some values that were great for an on-premises environment may not be optimal for a cloud-based
environment. When migrating the current on-premises parameters to Azure, verify that they can be set.
Some Azure Database for MySQL Flexible Server parameters cannot be modified. Verify the strategy before
making environment assumptions.
Custom environments can be tested against standard workloads by running various benchmarks using the
PHPBench tool.
• DBT2 Benchmark - DBT2 is an open source benchmark that mimics an OLTP application for a company
owning large amounts of warehouses. It contains transactions to handle New Orders, Order Entry, Order
Status, Payment and Stock handling
• SysBench Benchmark Tool - Sysbench is a popular open source benchmark to test open source DBMSs.
More Common sets of tests typically utilize TPC benchmarks such as TPC-H but there are many more types of
tests that can be run against the MySQL environment to test against specific workloads and patterns.
This image shows how to use tables in the sys schema to optimize MySQL queries.
Server Parameters
MySQL server parameters allow database architects and developers to optimize the MySQL engine for their
specific application workloads. One of the advantages of Flexible Server is the large number of server parameters
exposed by the service. Some important exposed parameters are listed below, but storage and compute tiers
affect the possible parameter values. Consult the Microsoft documentation for more information.
Some parameters that cannot be configured at the server level can be configured at the connection level.
Moreover, dynamic parameters can be changed without restarting the server, while modifying static parameters
warrants a restart.
• log_bin_trust_function_creators is enabled by default and indicates whether users can create triggers
• innodb_buffer_pool_size indicates the size of the buffer pool, a cache for tables and indexes
For this parameter, consult the Microsoft documentation, as the database compute tier affects the
parameter value range
The graph above reflects the performance improvements of thread pooling for a 16 vCore, 64 GiB
memory Flexible Server instance. The x-axis represents the number of connections, and the y-axis
represents the number of queries served per second (QPS). Read the associated Microsoft
TechCommunity post for more details
– Microsoft only recommends this change for database instances with more than 335 GB of
provisioned storage
Caching
Utilizing resources such as CPU, memory, disk (read/write access) and network can factor into how long an
application request takes to process. Being able to remove deterministic actions (ex: the same function/API call
does not change) within a certain set of time is an important pattern to implement in your various application
layers. Caching reduces the latency and contention that is associated with handling large volumes of concurrent
requests in the original data store.
Caching is a common technique that aims to improve the performance and scalability of a system. It does this by
temporarily copying frequently accessed data to fast storage that’s located close to the application.
Caching guidance
This caching option is a common pattern for when applications have users scattered all over the world. By
distributing the same files and content to locations that are closest to those users, the users will see improved
latency and perceived application performance.
Memory cache
Access to data in memory is much faster compared to retrieving data from disk. It is an effective means for storing
modest amounts of static data, since the size of a cache is typically constrained by the amount of memory
available on the machine hosting the process.
Local memory
If an application has access to local memory, it can utilize that memory to cache its data and access it more
quickly than going to disk or over the network. However, if the memory available to the application is less than
ideal (potentially driven by operating system or hardware limits), another caching option must be chosen. If the
application requires exceptionally low access rates, it will be necessary to send the data to a memory server.
Redis Cache
A common piece of software that helps with caching is called Redis cache. As with all pieces of software, it can be
run on-premises, in a virtual machine in the cloud (IaaS), or even as a platform-as-a-service offering (PaaS).
Redis cache works by putting data into memory via key/value pairs. The application will typically serialize the data
and then hand it off to Redis for quick retrieval later. The Redis cache should be located close to the application.
Query results should be retrieved and forwarded quickly.
Azure Cache for Redis is a platform as a service Microsoft Azure-hosted Redis environment that provides several
levels of service such as Enterprise, Premium, Standard, and Basic tiers.
Azure CDN also supports dynamic site acceleration, optimizing the network path from clients to the server
through POP sites, pre-fetches images and scripts, and more.
08 / Summary
After developers benchmark their MySQL Flexible Server workloads, they can tune server parameters, scale
compute tiers, and optimize their application containers to improve performance. Through Azure Monitor and
KQL queries, teams monitor the performance of their workloads.
Caching is a very common way to increase the performance of applications. Through disk or memory-based
cache, a developer and architect should always be on the lookout for deterministic areas that can be cached.
Azure CDN provides caching via POP servers to users of global-scale web apps.
Lastly, an important balance should be struck between performance of the cache and costs.
Checklist
• Monitor for slow queries.
Connectivity issues
Both server misconfiguration issues and network access issues can prevent clients from connecting to an Azure
Database for MySQL instance. For some helpful connectivity suggestions, reference the Troubleshoot connection
issues to Azure Database for MySQL and Handle transient errors and connect efficiently to Azure Database for
MySQL articles.
Misconfiguration
• Error 1184: This error occurs after a user authenticates with the database instance, but before they execute
SQL statements. The init_connect server parameter includes statements that execute before sessions are
initiated. Consequently, erroneous SQL statements in init_connect prevent clients from connecting.
– Resolution: Reset the value of init_connect using the Azure portal or SQL.
• Administrators use the database admin user specified during server creation to create new databases and
add new users. If the admin user credentials were not recorded, administrators can easily reset the admin
password using the Azure portal.
– Logging in with the administrator account can help debug other access issues, like confirming if a
given user exists.
• If connecting to Flexible Server via public access, ensure that firewall ACLs permit access from the client.
• Ensure that corporate firewalls do not block outbound connections to port 3306.
• Use a fully qualified domain name instead of an IP address in connection strings. This type of
configuration is especially important with Azure Database for MySQL Single Server instances, which use
gateways to route incoming requests to database servers. It is possible to use the gateway public IP
address in your applications.
Warning: However, as Microsoft plans to retire older gateways, you are responsible for updating
the gateway IP address in your applications. It is less error-prone to work with the FQDN.
– Network Watcher works well with other networking utilities, like the Unix traceroute tool
Resource issues
If the application experiences transient connectivity issues, perhaps the resources of the Azure Database for
MySQL instance are constrained. Monitor resource usage and determine whether the instance needs to be scaled
up.
• Azure Database for MySQL does not support the MySQL SUPER privilege and the DBA role. This may
affect how some applications operate.
– Error 1419: By default, MySQL instances with binary logging enabled for replication require
function creators to have the SUPER privilege to avoid privilege escalation attacks.
– Error 1227: This error occurs when creating stored procedures or views with DEFINER statements.
• Resolution: If you encounter this error while migrating schema objects from an on-
premises MySQL instance, remove the DEFINER statements manually from the database
dump.
• Direct file system access is not available to clients. This means that SELECT ... INTO OUTFILE commands
are unsupported.
• Only the InnoDB and MEMORY storage engines are supported. This may affect older data warehousing
and web applications based on the non-transactional MyISAM engine. Consult the MySQL documentation
to learn how to convert your MyISAM tables to InnoDB and make them run optimally.
Platform issues
• On occasion, Azure experiences outages. Use Azure Service Health to determine if an Azure outage
impacts MySQL workloads in your region or datacenter.
• Azure’s periodic updates can impact the availability of applications. Flexible Server allows administrators
to set custom maintenance schedules.
– To provide resiliency against more severe failures, like Azure service outages, implement the
circuit breaker pattern to avoid wasting application resources on operations that are likely to fail
• Network requests taking a long time? Troubleshoot slow app performance issues in Azure App Service
• In Azure App Service, certain settings are available to the deployment or runtime environment as
environment variables. Some of these settings can be customized when configuring the app settings.
Environment variables and app settings in Azure App Service
App debugging
Following software development best practices makes your code simpler to develop, test, debug, and deploy.
Here are some strategies to resolve application issues.
• Use logging utilities wisely to help troubleshoot failures without impairing app performance. Structured
logging utilities, like PHP’s native logging functions or third-party tools, such as KLogger, can write logs to
the console, to files, or to central repositories. Monitoring tools can parse these logs and alert anomalies.
• In development environments, remote debugging tools like XDebug may be useful. You can set
breakpoints and step through code execution. Apps running on Azure App Service PHP and Container
instances can take advantage of XDebug.
– Users of Visual Studio Code can install XDebug’s PHP Debug extension.
• To debug slow PHP applications, consider using Application Performance Monitoring solutions like Azure
Application Insights, which integrates with Azure Monitor. Here are a few common culprits for low-
performing PHP apps.
– Configuring web servers poorly, such as by choosing a suboptimal number of worker processes to
serve user requests
– Disabling opcode caching, requiring PHP to compile code files to opcodes every request
• Write tests to ensure that applications function as intended when code is modified. Review the 07 /
Testing document for more information about different testing strategies. Tests should be included in
automated release processes.
• Generally, all cloud applications should include connection retry logic, which typically responds to
transient issues by initiating subsequent connections after a delay.
Additional support
• In the Azure portal, navigate to the Diagnose and solve problems tab of your Azure Database for MySQL
instance for suggestions regarding common connectivity, performance, and availability issues.
This experience integrates with Azure Resource Health to demonstrate how Azure outages affect your
provisioned resources.
• If none of the above resolve the issue with the MySQL instance, send a support request from the Azure
portal.
Recommended content
• Troubleshoot connection issues to Azure Database for MySQL
• Handle transient errors and connect efficiently to Azure Database for MySQL
• Troubleshoot errors commonly encountered during or post migration to Azure Database for MySQL
• Azure Community Support Ask questions, get answers, and connect with Microsoft engineers and Azure
community experts
09 / Summary
This section helped pinpoint some of the most common issues a team may run into when hosting your MySQL
based applications in the cloud. These included items from connectivity, deployment, and performance.
Checklist
• Understand the OSI model and how it can help troubleshoot issues.
• Start at the bottom of the OSI model and work your way up.
• Network connectivity issues can exist anywhere between client and server.
High availability
Flexible Server implements high availability by provisioning another VM to serve as a standby. It is possible to
provision this secondary Flexible Server VM in another availability zone, as shown below. This HA option is only
supported for Azure regions with availability zones. While this option does provide redundancy against zonal
failure, there is more latency between the zones that affects replication.
Watch: High Availability [9 of 16] | Azure Database for MySQL - Beginners Series
Azure provides HA within a single zone to compensate for the latency challenges. In this configuration, both the
primary node and the standby node are in the same zone. All Azure regions support this configuration. Of course,
it does not insulate against zonal failure.
Both of these HA solutions have transparent failover. In a failover event, the standby server becomes the primary
server, and DNS records point to the new primary. If the old primary comes back online, it becomes the
secondary.
Note: Replication is not synchronous to avoid the performance penalty of synchronous replication. A
transaction committed to the primary node is not necessarily committed to the secondary node; the secondary
node is brought up to the latest committed transaction during failover.
To learn more about HA with MySQL Flexible Server, consult the documentation.
This image demonstrates a possible cross-region HA scenario using two virtual networks.
The virtual networks are peered to provide network connectivity for MySQL native replication. As the image
indicates, developers can employ MySQL native replication for scenarios like replicating from an on-premises
primary to an Azure secondary.
Replication
Replication in Flexible Server allows applications to scale by providing read-only replicas to serve queries while
dedicating write operations to the main Flexible Server instance.
Watch: Replication [10 of 16] | Azure Database for MySQL - Beginners Series
Replication from the main instance to the read replicas is asynchronous. Consequently, there is a lag between the
source instance and the replicas. Microsoft estimates that this lag typically ranges between a few seconds to a few
minutes.
Warning: Replication is not a high availability strategy. Consult the BCDR document for more details.
Replication is designed to improve application performance, so it does not support automatic failover or
bringing replicas up to the latest committed transaction during failover.
Replication is only supported in the General Purpose and Business Critical tiers of Flexible Server. Also, it is
possible to promote a read replica to being a read-write instance. However, that severs the replication link
between the main instance and the former replica, as the former replica cannot return to being a replica.
Read replicas
Read replicas can be used to increase the MySQL read throughput, improve performance for regional users, and
implement disaster recovery. There is a cost. When creating one or more read replicas, be aware that additional
charges will apply for the same compute and storage as the primary server.
Warning: If an administrator or bad actor deletes the server in the Azure Portal or via automated methods,
all backups and read replicas will also be deleted. Resource locks must be created on the Azure Database for
MySQL resource group to add an extra layer of deletion prevention to the instances.
Regional failure
In case of a rare regional failure event, geo-redundant backups or a read replica can be used to get the data
workloads running again. It is best to have both geo-replication and a read replica available for the best
protection against unexpected regional failures.
Note: Changing the database server region also means the endpoint will change and application
configurations will need to be updated accordingly.
Load Balancers
If the application is made up of many different instances around the world, it may not be feasible to update all of
the clients. A load balancer may assist in this challenge. Load balancing focuses on distributing load (incoming
network traffic) across a group of backend resources or servers. Utilize an Azure Load Balancer or Application
Gateway to implement a seamless failover functionality. Although helpful and time-saving, these tools are not
required for regional failover capability.
Use cases
Load balancer
Often, developers use load balancers, like ProxySQL, to direct read operations to read replicas automatically.
ProxySQL can run on an Azure VM or Azure Kubernetes Service.
Tip: Moreover, analytical systems often benefit from read replicas. BI tools can connect to read replicas,
while data is written to the main instance and replicated to the read replicas asynchronously.
Read replicas
Using read replicas also helps with microservice architecture implementations. The image below demonstrates
how APIs that require read-only access data can connect to read replicas. APIs that modify data can use the
primary database instance.
• Azure CLI
Watch: Backup and Restore [8 of 16] | Azure Database for MySQL - Beginners Series
If an unforeseen event occurs, administrators should have the ability to restore data to a point in time called the
Recovery Point Objective (RPO) and in a reasonable amount of time called the Recovery Time Objective (RTO).
Backup
Azure Database for MySQL takes automatic backups of data and transaction log files. These backups can be
stored in locally-redundant storage (replicated multiple times in a datacenter); zone-redundant storage (multiple
copies are stored in two separate availability zones in a region); and geo-redundant storage (multiple copies are
stored in two separate Azure regions).
Azure Database for MySQL supports automatic backups for 7 days by default. It may be appropriate to modify this
to the current maximum of 35 days. It is important to be aware that if the value is changed to 35 days, there will
be charges for any extra backup storage over 1x of the storage allocated. Data file backups are taken once daily,
while transaction log backups are taken every five minutes.
There are several current limitations to the database backup feature as described in the Backup and restore in
Azure Database for MySQL docs article. It is important to understand them when deciding what additional
strategies should be implemented.
• Tiers that allow up to 4TB have a full backup once per week, differential twice a day, and logs every five
minutes
Restore
Redundancy (local or geo) must be configured during server creation. However, a geo-restore can be performed
and allows the modification of these options during the restore process. Performing a restore operation will
temporarily stop connectivity, and any applications will be down during the restore process.
During a database restore, any supporting items outside of the database will also need to be restored. Review the
migration process. See Perform post-restore tasks for more information.
Lastly, note that performing a restore from a backup provisions a new Flexible Server instance. Most of the new
server’s configuration is inherited from the old server, though it depends on the type of restore performed.
Learn more about backup and restore in Flexible Server from the Microsoft documentation.
• Azure CLI samples for Azure Database for MySQL - Flexible Server
Service maintenance
Like any Azure service, Flexible Server receives patches and functionality upgrades from Microsoft. To ensure that
planned maintenance does not blindside administrators, Azure provides them control over when patching occurs.
With Flexible Server, administrators can specify a custom Day of week and Start time for maintenance, or they
can let the platform choose a day of week and time. If the maintenance schedule is chosen by the platform,
maintenance will always occur between 11 PM and 7 AM in the region’s time zone.
See this list from Microsoft to determine the physical location of Azure regions and thus the regional time zone.
Azure always rolls out updates to servers with platform-managed schedules before instances with custom
schedules. Platform-managed schedules allow developers to evaluate Flexible Server feature improvements in
non-production environments. Moreover, maintenance events are relatively infrequent; there are typically 30 days
of gap unless a critical security fix must be applied.
Use Azure Service Health to view upcoming infrastructure updates and set notifications. Refer to the links at the
end of the document.
Single Server does not support custom schedules for maintenance. Azure notifies administrators 72 hours before
the maintenance event.
Retired MySQL engine versions not supported in Azure Database for MySQL
Warning: It is important to be aware the upgrade process can be random. During deployment, the MySQL
server workloads will stop be processed on the server. Plan for these downtimes by rerouting the workloads to a
read replica in the event the particular instance goes into maintenance mode.
Note: This style of failover architecture may require changes to the applications data layer to support this
type of failover scenario. If the read replica is maintained as a read replica and is not promoted, the application
will only be able to read data and it may fail when any operation attempts to write information to the database.
The planned maintenance notification feature will inform resource owners up to 72 hours in advance of
installation of an update or critical security patch. Database administrators may need to notify application users of
planned and unplanned maintenance.
Note: Azure Database for MySQL maintenance notifications are incredibly important. The database
maintenance can take the database and connected applications down for a short period of time.
Checklist
• Perform backups regularly, ensure the backup frequency meets requirements.
• Setup read replicas for read intensive workloads and regional failover.
Readers should review additional guide chapters for a more comprehensive understanding.
• 05 / Monitoring
• 07 / Testing
Consult the Azure Well-Architected Framework for more information regarding the core principles of efficient
cloud workloads. You can assess your existing Azure workloads for Well-Architected Framework compliance with
the Azure Well-Architected Review utility.
1. Co-locate resources
Locating Azure services in the same region minimizes network traffic costs and network latency. Flexible Server
supports co-location in the same region and co-location in the same Availability Zone for regions that support
Availability Zones. MySQL Flexible Server couples well with zonal services, like Virtual Machines.
• ProxySQL on a VM
• ProxySQL on AKS
Developers can identify container resource issues using monitoring utilities, like Container insights, which supports
Azure Kubernetes Service, Azure Container Instances, on-premises Kubernetes clusters, and more.
• Identify AKS containers that are running on the node and their average processor and memory utilization.
This knowledge can help you identify resource bottlenecks.
• Review the resource utilization of workloads running on the host that are unrelated to the standard
processes that support the pod.
Microsoft also recommends securing data in motion through SSL for applications that support SSL connectivity.
Legacy applications should only use lower SSL versions or disable SSL connectivity in secure network
environments.
Applications must first determine if a fault is transient or more persistent. Typically, API responses indicate the
nature of the issue, sometimes even specifying a retry interval. If the fault is transient, applications must retry
requests without consuming excessive resources. Common retry strategies including sending requests at regular
intervals, exponential intervals, or random intervals. If a given number of retry requests fail, applications consider
the operation failed.
Azure SDKs typically provide native support for retrying service requests. Consult the documentation’s list of per-
service retry recommendations.
For some ORMs that are commonly used with MySQL databases, like PHP’s PDO MySQL, it may be necessary to
write custom retry code that retries database connections if particular MySQL error codes are thrown.
• Burstable:
• General Purpose:
– Intended for high-throughput transactional and analytical workloads, like real-time data
processing
Flexible Server instances can be resized after creation. Azure stops database VM instances and needs up to 120
seconds to scale compute resources.
Use Azure Monitor Metrics to determine if you need to scale your Flexible Server instance. Monitor metrics like
Host CPU percent, Active Connections, IO percent, and Host Memory Percent to make your scaling decisions.
To test database performance under realistic application load, consider utilities like sysbench.
11 / Summary
The preceding best practices are a collection of the most common items that architects and developers may
employ to improve the performance, security and availability of their Azure Database for MySQL applications. Be
sure to review if you have followed all the recommended best practices and if you discover they have not been
followed, try to implement them as soon as possible to ensure the integrity of your applications and satisfaction of
your users.
The Azure Architecture center provides many different examples of how to create different architectures. Although
some of them utilize other database persistence technologies, these could easily be substituted with Azure
Database for MySQL - Flexible Server.
Sample architectures
The following are a few examples of architectures using different patterns and focused on various industries from
the Azure Architecture Center.
– Azure App Service to host gaming APIs and Azure Database for MySQL. Firms can perform
analysis on gaming data in Azure Database for MySQL using Azure HDInsight.
Scalable web and mobile applications using Azure Database for MySQL
• Scalable web and mobile applications using Azure Database for MySQL: This generic architecture utilizes
the scaling capabilities (vertical and horizontal) of Azure App Service and MySQL Flexible Server.
12 / Summary
Many customers have built scalable resilient architectures using Azure Database for MySQL. Developers can build
basic two-tier and three-tier architectures to more advanced container-based and event-driven MySQL based
architectures.
At the very core, an application will consume CPU, memory, disk and network. Finding the right target hosting
platform while balancing costs is a vital skill. Developers should leverage the examples provided throughout this
guide to accelerate their learning and adoption journey.
Checklist
• Reference architectures can provide ideas on how to use a product. Start to learn from successful
deployments.
Case studies
The following are a set of case studies from the Microsoft Customer Stories page focused on the usage of Azure
Database for MySQL.
Minecraft
Minecraft migrated from AWS Aurora to Azure Database for MySQL for its Realms service to improve performance
and reduce costs. Minecraft moved over 1 TB of data, distributed across 13 databases, serving over 6k requests
per second during the migration. Minecraft utilized the Azure Database Migration Service six-month free offer to
save costs.
Minecraft also migrated its frontend servers to Azure to take advantage of Azure’s global footprint. This migration
also improved developer productivity through smaller code footprints and simpler deployments.
Automobile Retail
The retailer ran MySQL database on Red Hat Enterprise Linux with a Java Spring Boot application on the backend
and a Vue.js on the frontend. The environment did not have the capability to scale up and down as needed to
cope with this fluctuation in the market, and 30% of its resources were underutilized. As a result, the retailer was
overpaying and unnecessarily bleeding valuable capital.
The MySQL database was modernized with Azure Database for MySQL with a read replica to support the reporting
needs of the business.
Linked Brain
In November 2019, a Microsoft gaming industry representative visited Linked Brain to explain Microsoft Azure
services and FastTrack for Azure. Features fitted perfectly with Linked Brain’s goal of building game systems with
PaaS, and the company decided to officially adopt Microsoft Azure.
We learned Flexible Server could scale up and down without stoppages, offer backup capabilities, and deliver I/O
capacity proportionate to storage size, making it easy to boost performance as data accumulates. Azure also
offers regional disaster recovery as a standard benefit—an option which requires another instance fee on Amazon
RDS.”
In the Internet of Things (IoT) age, organizations must share proprietary data quickly while maintaining control,
security, and compliance. T-Systems, a Deutsche Telekom division, worked with expert partner Ultra Tendency to
meet that need, using Microsoft Azure and Azure Database for PostgreSQL to help create the Telekom Data
Intelligence Hub, a data marketplace for data sharing that includes built-in analytics tools.
“We were looking for managed database solutions,” says Robert Neumann, Chief Executive Officer at Ultra
Tendency. “With Azure database services, we wouldn’t have to manage uptime, backup, and recovery scenarios,
and we could make the platform faster and more reliable.”
The execution layer of Data Intelligence Hub runs entirely on Azure database services, using the Azure Database
for PostgreSQL and Azure Database for MySQL services to support data availability without having to maintain a
database operations infrastructure.
Children’s Mercy Kansas City, an award-winning hospital and research institute, manages one of the leading
genome sequencing centers in the United States. To better support researchers, Children’s Mercy is working with
Microsoft and Pacific Biosciences to create a scalable, sharable, cloud-based data hub for vital research into
pediatric diseases, built on Microsoft Genomics and Azure. It’s already garnering praise from the genomics
research community and has the potential to accelerate vital clinical care for children.
The hospital and research institute had an existing relationship with Microsoft, so when researchers saw
sequencing data begin to push toward the CMRI datacenter’s storage limits, the organization chose to support its
genomic data platform with Microsoft Genomics, Azure Database for MySQL, and Azure infrastructure as a service
(IaaS) resources.
GeekWire
Based in Seattle, Washington, GeekWire is a rapidly growing technology news site with a global readership. In
addition to covering the latest innovation, GeekWire serves the Pacific Northwest tech community with events, a
job board, startup resources, a weekly radio show, and more. As its popularity and site traffic increased, so did
performance concerns. To gain better scalability and performance, GeekWire decided to migrate its WordPress
13 / Summary
Similar to the reference architecture, case studies provide a view into how other organizations are building
applications using MySQL that could be appropriate and similar to how a developer may be thinking of building
their own application. Although they may not go into as much depth as reference architectures, they certainly
provide a means of generating ideas.
Checklist
• Understand the most common uses of a product.
• Justify and validate your use cases based on the use case studies.
Summary of tasks
• Have the right tools available.
• Ensure up policies and procedures are setup and configured for auditing application and database
workloads.
14 / Final Summary
This guide was designed to provide insightful and rich sets of information on how to get started with developing
applications with Azure Database for MySQL. After reading through all the sections, a developer will have nurtured
a foundation for how to get set up with the right tools and how to make decisions on target deployment models.
This guide provided several sample architectures, deployment models and real-world customer references of
using Azure Database for MySQL that can be referenced in platform selection decisions.
As a final note, although there are several options for hosting MySQL in Azure, the recommended and preferred
method is to utilize Azure Database for MySQL Flexible Server for its rich set of features and flexibility.
• Review homepage
• Documentation
• Tutorial
Feel free to search for a Microsoft Partner or Microsoft MVP to help with finding the most appropriate migration
strategy.
Browse the technical forums and social groups for more detailed real-world information:
This document is provided “as-is”. Information and views expressed in this document, including URL and other
Internet Web site references, may change without notice.