教程:在 Azure 中构建 PHP 和 MySQL 应用Tutorial: Build a PHP and MySQL app in Azure

Azure 应用服务提供高度可缩放、自修复的 Web 托管服务。Azure App Service provides a highly scalable, self-patching web hosting service. 本教程介绍如何在 Azure 中创建 PHP 应用,并将其连接到 MySQL 数据库。This tutorial shows how to create a PHP app in Azure and connect it to a MySQL database. 完成本教程后,Azure 应用服务中将会运行一个 Laravel 应用。When you're finished, you'll have a Laravel app running on Azure App Service.

在 Azure 应用服务中运行的 PHP 应用

本教程介绍如何执行下列操作:In this tutorial, you learn how to:

  • 在 Azure 中创建 MySQL 数据库Create a MySQL database in Azure
  • 将 PHP 应用连接到 MySQLConnect a PHP app to MySQL
  • 将应用部署到 AzureDeploy the app to Azure
  • 更新数据模型并重新部署应用Update the data model and redeploy the app
  • 从 Azure 流式传输诊断日志Stream diagnostic logs from Azure
  • 在 Azure 门户中管理应用Manage the app in the Azure portal

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

完成本教程:To complete this tutorial:

准备本地 MySQLPrepare local MySQL

此步骤在本地 MySQL 服务器供中创建一个数据库,以便在本教程中使用。In this step, you create a database in your local MySQL server for your use in this tutorial.

连接到本地 MySQL 服务器Connect to local MySQL server

在终端窗口中连接到本地 MySQL 服务器。In a terminal window, connect to your local MySQL server. 可使用此终端窗口运行本教程中的所有命令。You can use this terminal window to run all the commands in this tutorial.

mysql -u root -p

当系统提示输入密码时,请输入 root 帐户的密码。If you're prompted for a password, enter the password for the root account. 如果不记得自己的 Root 帐户密码,请参阅 MySQL:如何重置 Root 密码If you don't remember your root account password, see MySQL: How to Reset the Root Password.

如果命令成功运行,则表示 MySQL 服务器正在运行。If your command runs successfully, then your MySQL server is running. 否则,请确保遵循 MySQL 安装后步骤启动本地 MySQL 服务器。If not, make sure that your local MySQL server is started by following the MySQL post-installation steps.

在本地创建数据库Create a database locally

mysql 提示中创建数据库。At the mysql prompt, create a database.

CREATE DATABASE sampledb;

键入 quit 退出服务器连接。Exit your server connection by typing quit.

quit

在本地创建 PHP 应用Create a PHP app locally

此步骤创建一个 Laravel 示例应用程序、配置其数据库连接,并在本地运行该应用程序。In this step, you get a Laravel sample application, configure its database connection, and run it locally.

克隆示例Clone the sample

在终端窗口中,通过 cd 转到工作目录。In the terminal window, cd to a working directory.

运行下列命令,克隆示例存储库。Run the following command to clone the sample repository.

git clone https://github.com/Azure-Samples/laravel-tasks

通过 cd 转到克隆目录。cd to your cloned directory. 安装所需程序包。Install the required packages.

cd laravel-tasks
composer install

配置 MySQL 连接Configure MySQL connection

在存储库根路径中,创建名为 .env 的文本文件。In the repository root, create a text file named .env. 复制下列变量到 .env 文件。Copy the following variables into the .env file. 请将 <root_password> 占位符替换为 MySQL 根用户的密码。Replace the <root_password> placeholder with the MySQL root user's password.

APP_ENV=local
APP_DEBUG=true
APP_KEY=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=sampledb
DB_USERNAME=root
DB_PASSWORD=<root_password>

有关 Laravel 如何使用 .env 文件的信息,请参阅 Laravel 环境配置For information on how Laravel uses the .env file, see Laravel Environment Configuration.

在本地运行示例Run the sample locally

运行 Laravel 数据库迁移,创建应用程序所需的表。Run Laravel database migrations to create the tables the application needs. 若要查看迁移中创建了哪些表,请查看 Git 存储库中的 database/migrations 目录。To see which tables are created in the migrations, look in the database/migrations directory in the Git repository.

php artisan migrate

生成新的 Laravel 应用程序密钥。Generate a new Laravel application key.

php artisan key:generate

运行应用程序。Run the application.

php artisan serve

在浏览器中导航到 http://localhost:8000Navigate to http://localhost:8000 in a browser. 在页面中添加一些任务。Add a few tasks in the page.

PHP 已成功连接到 MySQL

若要停止 PHP 服务器,请在终端中键入 Ctrl + CTo stop the PHP server, type Ctrl + C in the terminal.

在 Azure 中创建 MySQLCreate MySQL in Azure

此步骤在 Azure Database for MySQL 中创建一个 MySQL 数据库。In this step, you create a MySQL database in Azure Database for MySQL. 稍后需要将 PHP 应用程序配置为连接到此数据库。Later, you configure the PHP application to connect to this database.

创建资源组Create a resource group

资源组是在其中部署和管理 Azure 资源(如 Web 应用、数据库和存储帐户)的逻辑容器。A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed. 例如,可以选择在使用完之后通过一个简单的步骤删除整个资源组。For example, you can choose to delete the entire resource group in one simple step later.

在 Azure CLI 中,使用 az group create 命令创建资源组。In the Azure CLI, create a resource group with the az group create command. 以下示例在“中国北部”位置创建名为“myResourceGroup”的资源组。The following example creates a resource group named myResourceGroup in the China North location. 要查看“免费”层中应用服务支持的所有位置,请运行 az appservice list-locations --sku FREE 命令。To see all supported locations for App Service in Free tier, run the az appservice list-locations --sku FREE command.

az group create --name myResourceGroup --location "China North"

通常在附近的区域中创建资源组和资源。You generally create your resource group and the resources in a region near you.

此命令完成后,JSON 输出会显示资源组属性。When the command finishes, a JSON output shows you the resource group properties.

创建 MySQL 服务器Create a MySQL server

在 Windows 终端中,使用 az mysql server create 命令在 Azure Database for MySQL 中创建一个服务器。In the windows terminal, create a server in Azure Database for MySQL with the az mysql server create command.

在下列命令中,用唯一的服务器名称替换 <mysql_server_name> 占位符,用用户名替换 <admin_user> 占位符,并用密码替换 <admin_password> 占位符。In the following command, substitute a unique server name for the <mysql_server_name> placeholder, a user name for the <admin_user>, and a password for the <admin_password> placeholder. 此服务器名称用作 MySQL 终结点 (https://<mysql_server_name>.mysql.database.azure.cn) 的一部分,因此需在 Azure 的所有服务器中保持唯一。The server name is used as part of your MySQL endpoint (https://<mysql_server_name>.mysql.database.azure.cn), so the name needs to be unique across all servers in Azure.

az mysql server create --resource-group myResourceGroup --name <mysql_server_name> --location "China East" --admin-user <admin_user> --admin-password <admin_password> --sku-name B_Gen5_1

备注

因为本教程中考虑多个凭据,为避免混淆,--admin-user--admin-password 设置为虚构值。Since there are several credentials to think about in this tutorial, to avoid confusion, --admin-user and --admin-password are set to dummy values. 在生产环境中,为 Azure 中的 MySQL 服务器选择适当的用户名和密码时,请遵循安全最佳做法。In a production environment, follow security best practices when choosing a good username and password for your MySQL server in Azure.

创建 MySQL 服务器后,Azure CLI 会显示类似于以下示例的信息:When the MySQL server is created, the Azure CLI shows information similar to the following example:

{
  "location": "chinaeast",
  "name": "<mysql_server_name>",
  "resourceGroup": "myResourceGroup",
  "sku": {
    "additionalProperties": {},
    "capacity": 1,
    "family": "Gen5",
    "name": "B_Gen5_1",
    "size": null,
    "tier": "GeneralPurpose"
  },
  "sslEnforcement": "Enabled",
  ...    +  
  -  < Output has been truncated for readability >
}

配置服务器防火墙Configure server firewall

在 Windows 终端中,使用 az mysql server firewall-rule create 命令创建 MySQL 服务器的防火墙规则,以便建立客户端连接。In the windows terminal, create a firewall rule for your MySQL server to allow client connections by using the az mysql server firewall-rule create command. 若同时将起始 IP 和结束 IP 设置为 0.0.0.0,防火墙将仅对其他 Azure 资源开启。When both starting IP and end IP are set to 0.0.0.0, the firewall is only opened for other Azure resources.

az mysql server firewall-rule create --name allAzureIPs --server <mysql_server_name> --resource-group myResourceGroup --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0

提示

你甚至可以让防火墙规则更严格,即只使用应用所使用的出站 IP 地址You can be even more restrictive in your firewall rule by using only the outbound IP addresses your app uses.

在 Windows 终端中再次运行该命令(将 <your_ip_address> 替换为你的本地 IPv4 IP 地址),以便允许从本地计算机进行访问。In the windows terminal, run the command again to allow access from your local computer by replacing <your_ip_address> with your local IPv4 IP address.

az mysql server firewall-rule create --name AllowLocalClient --server <mysql_server_name> --resource-group myResourceGroup --start-ip-address=<your_ip_address> --end-ip-address=<your_ip_address>

在本地连接到生产 MySQL 服务器Connect to production MySQL server locally

在本地终端窗口中,连接到 Azure 中的 MySQL 服务器。In the local terminal window, connect to the MySQL server in Azure. 使用前面为 <mysql_server_name> 指定的值。Use the value you specified previously for <mysql_server_name>. 出现输入密码的提示时,请使用在 Azure 中创建数据库时指定的密码。When prompted for a password, use the password you specified when you created the database in Azure.

mysql -u <admin_user>@<mysql_server_name> -h <mysql_server_name>.mysql.database.azure.cn -P 3306 -p <PASSWORD> --ssl-mode=REQUIRED --ssl-ca=<PATH_TO_PEM>

创建生产数据库Create a production database

mysql 提示中创建数据库。At the mysql prompt, create a database.

CREATE DATABASE sampledb;

创建具有权限的用户Create a user with permissions

创建一个名为 phpappuser 的数据库用户并向其授予 sampledb 数据库中的所有特权。Create a database user called phpappuser and give it all privileges in the sampledb database. 同样,为方便学习教程,请使用 MySQLAzure2017 作为密码。Again, for simplicity of the tutorial, use MySQLAzure2017 as the password.

CREATE USER 'phpappuser' IDENTIFIED BY 'MySQLAzure2017'; 
GRANT ALL PRIVILEGES ON sampledb.* TO 'phpappuser';

键入 quit 退出服务器连接。Exit the server connection by typing quit.

quit

将应用连接到 Azure MySQLConnect app to Azure MySQL

此步骤将 PHP 应用程序连接到在 Azure Database for MySQL 中创建的 MySQL 数据库。In this step, you connect the PHP application to the MySQL database you created in Azure Database for MySQL.

配置数据库连接Configure the database connection

在存储库根路径中创建一个 .env.production 文件,并在其中复制以下变量。In the repository root, create an .env.production file and copy the following variables into it. 替换 DB_HOSTDB_USERNAME 中的占位符 <mysql_server_name>Replace the placeholder <mysql_server_name> in both DB_HOST and DB_USERNAME.

APP_ENV=production
APP_DEBUG=true
APP_KEY=

DB_CONNECTION=mysql
DB_HOST=<mysql_server_name>.mysql.database.azure.cn
DB_DATABASE=sampledb
DB_USERNAME=phpappuser@<mysql_server_name>
DB_PASSWORD=MySQLAzure2017
MYSQL_SSL=true

保存更改。Save the changes.

提示

若要保护 MySQL 连接信息,此文件已从 Git 存储库(请参阅存储库根路径中的 .gitignore排除。To secure your MySQL connection information, this file is already excluded from the Git repository (See .gitignore in the repository root). 以后介绍如何将应用服务中的环境变量配置为连接到 Azure Database for MySQL 中的数据库。Later, you learn how to configure environment variables in App Service to connect to your database in Azure Database for MySQL. 有了环境变量,便不需要应用服务中的 .env 文件。With environment variables, you don't need the .env file in App Service.

配置 TLS/SSL 证书Configure TLS/SSL certificate

默认情况下,Azure Database for MySQL 强制执行来自客户端的 TLS 连接。By default, Azure Database for MySQL enforces TLS connections from clients. 若要连接到 Azure 中的 MySQL 数据库,必须使用 Azure Database for MySQL 提供的 .pem 证书To connect to your MySQL database in Azure, you must use the .pem certificate supplied by Azure Database for MySQL.

打开 config/database.php,将 sslmodeoptions 参数添加到 connections.mysql,如以下代码所示。Open config/database.php and add the sslmode and options parameters to connections.mysql, as shown in the following code.

'mysql' => [
    ...
    'sslmode' => env('DB_SSLMODE', 'prefer'),
    'options' => (env('MYSQL_SSL')) ? [
        PDO::MYSQL_ATTR_SSL_KEY    => '/ssl/BaltimoreCyberTrustRoot.crt.pem', 
    ] : []
],

在本教程中,为方便起见,证书 BaltimoreCyberTrustRoot.crt.pem 在存储库中提供。The certificate BaltimoreCyberTrustRoot.crt.pem is provided in the repository for convenience in this tutorial.

在本地测试应用程序Test the application locally

使用 .env.production 作为环境文件运行 Laravel 数据库迁移,在 Azure Database for MySQL 中的 MySQL 数据库内创建表。Run Laravel database migrations with .env.production as the environment file to create the tables in your MySQL database in Azure Database for MySQL. 请记住,在 Azure 中 .env.production 具有的 MySQL 数据库的连接信息。Remember that .env.production has the connection information to your MySQL database in Azure.

php artisan migrate --env=production --force

.env.production 目前还不包含有效的应用程序密钥。.env.production doesn't have a valid application key yet. 请在终端中为它生成一个新密钥。Generate a new one for it in the terminal.

php artisan key:generate --env=production --force

使用 .env.production 作为环境文件运行示例应用程序。Run the sample application with .env.production as the environment file.

php artisan serve --env=production

导航到 http://localhost:8000Navigate to http://localhost:8000. 如果页面可加载且未出错,则表示 PHP 应用程序正在连接到 Azure 中的 MySQL 数据库。If the page loads without errors, the PHP application is connecting to the MySQL database in Azure.

在页面中添加一些任务。Add a few tasks in the page.

PHP 已成功连接到 Azure Database for MySQL

在终端键入 Ctrl + C 可停止 PHP。To stop PHP, type Ctrl + C in the terminal.

提交更改Commit your changes

运行以下的 Git 命令,提交更改:Run the following Git commands to commit your changes:

git add .
git commit -m "database.php updates"

应用已可用于部署。Your app is ready to be deployed.

“部署到 Azure”Deploy to Azure

此步骤将已连接 MySQL 的 PHP 应用程序部署到 Azure 应用服务。In this step, you deploy the MySQL-connected PHP application to Azure App Service.

配置部署用户Configure a deployment user

可以使用“部署用户” 将 FTP 和本地 Git 部署到 Azure Web 应用。FTP and local Git can deploy to an Azure web app by using a deployment user. 配置部署用户之后,可对所有 Azure 部署使用此用户。Once you configure your deployment user, you can use it for all your Azure deployments. 帐户级部署用户名和密码不同于 Azure 订阅凭据。Your account-level deployment username and password are different from your Azure subscription credentials.

若要配置部署用户,请在 Azure Cloud Shell 中运行 az webapp deployment user set 命令。To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. 将 <username> 和 <password> 替换为部署用户名和密码。Replace <username> and <password> with a deployment user username and password.

  • 用户名必须在 Azure 中唯一,并且对于本地 Git 推送,不能包含“@”符号。The username must be unique within Azure, and for local Git pushes, must not contain the �@� symbol.
  • 密码必须至少为 8 个字符,且具有字母、数字和符号这三种元素中的两种。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

JSON 输出会将该密码显示为 nullThe JSON output shows the password as null. 如果收到 'Conflict'. Details: 409 错误,请更改用户名。If you get a 'Conflict'. Details: 409 error, change the username. 如果收到 'Bad Request'. Details: 400 错误,请使用更强的密码。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

请记录你要用于部署 Web 应用的用户名和密码。Record your username and password to use to deploy your web apps.

创建应用服务计划Create an App Service plan

使用 az appservice plan create 命令创建应用服务计划。Create an App Service plan with the az appservice plan create command.

以下示例在免费定价层中创建名为 myAppServicePlan 的应用服务计划:The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE

创建应用服务计划后,Azure CLI 会显示类似于以下示例的信息:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "China North",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "China North",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

创建 Web 应用Create a web app

myAppServicePlan 应用服务计划中创建一个 Web 应用。Create a web app in the myAppServicePlan App Service plan.

在 Azure CLI 中,可以使用 az webapp create 命令。在以下示例中,将 <app-name> 替换为全局唯一的应用名称(有效字符是 a-z0-9-)。In the Azure CLI, you can use the az webapp create command.In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -). 运行时设置为 PHP|7.3The runtime is set to PHP|7.3. 若要查看所有受支持的运行时,请运行 az webapp list-runtimesTo see all supported runtimes, run az webapp list-runtimes.

# Bash
az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "PHP|7.3" --deployment-local-git
# PowerShell
az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "PHP|7.3" --deployment-local-git

创建 Web 应用后,Azure CLI 会显示类似于以下示例的输出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.chinacloudsites.cn",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

现在你已经创建了一个新的空 Web 应用并启用了 Git 部署。You’ve created an empty new web app, with git deployment enabled.

备注

Git 远程的 URL 将显示在 deploymentLocalGitUrl 属性中,其格式为 https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git. 保存此 URL,后续将会用到。Save this URL as you need it later.

配置数据库设置Configure database settings

如前所述,可以使用应用服务中的环境变量连接到 Azure MySQL 数据库。As pointed out previously, you can connect to your Azure MySQL database using environment variables in App Service.

在 Windows 终端中,使用 az webapp config appsettings set 命令将环境变量设置为应用设置。In the windows terminal, you set environment variables as app settings by using the az webapp config appsettings set command.

使用以下命令可以配置应用设置 DB_HOSTDB_DATABASEDB_USERNAMEDB_PASSWORDThe following command configures the app settings DB_HOST, DB_DATABASE, DB_USERNAME, and DB_PASSWORD. 替换占位符 <appname> 和 <mysql_server_name>。Replace the placeholders <appname> and <mysql_server_name>.

az webapp config appsettings set --name <app_name> --resource-group myResourceGroup --settings DB_HOST="<mysql_server_name>.mysql.database.azure.com" DB_DATABASE="sampledb" DB_USERNAME="phpappuser@<mysql_server_name>" DB_PASSWORD="MySQLAzure2017" MYSQL_SSL="true"

可以使用 PHP getenv 方法访问这些设置。You can use the PHP getenv method to access the settings. Laravel 代码使用 env 包装器,而不是 PHP getenvthe Laravel code uses an env wrapper over the PHP getenv. 例如,config/database.php 中的 MySQL 配置如下代码所示:For example, the MySQL configuration in config/database.php looks like the following code:

'mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'forge'),
    'username'  => env('DB_USERNAME', 'forge'),
    'password'  => env('DB_PASSWORD', ''),
    ...
],

配置 Laravel 环境变量Configure Laravel environment variables

在应用服务中,Laravel 需要应用程序密钥。Laravel needs an application key in App Service. 可以使用应用设置来配置该密钥。You can configure it with app settings.

在本地终端窗口中,使用 php artisan 生成新的应用程序密钥,但不要将它保存到 .envIn the local terminal window, use php artisan to generate a new application key without saving it to .env.

php artisan key:generate --show

在 Windows 终端中,使用 az webapp config appsettings set 命令在应用服务应用中设置应用程序密钥。In the windows terminal, set the application key in the App Service app by using the az webapp config appsettings set command. 替换占位符 <appname><outputofphpartisankey:generate>Replace the placeholders <appname> and <outputofphpartisankey:generate>.

az webapp config appsettings set --name <app_name> --resource-group myResourceGroup --settings APP_KEY="<output_of_php_artisan_key:generate>" APP_DEBUG="true"

当部署的应用遇到错误时,APP_DEBUG="true" 将告知 Laravel 返回调试信息。APP_DEBUG="true" tells Laravel to return debugging information when the deployed app encounters errors. 在运行生产应用程序时,请将其设置为 false,这样会更安全。When running a production application, set it to false, which is more secure.

设置虚拟应用程序路径Set the virtual application path

设置应用的虚拟应用程序路径。Set the virtual application path for the app. 需要执行此步骤的原因是 Laravel 应用程序生命周期在 public 目录中开始,而不是在应用程序的根目录中开始。This step is required because the Laravel application lifecycle begins in the public directory instead of the application's root directory. 无需手动配置虚拟应用程序路径,生命周期在根目录中开始的其他 PHP 框架也能正常工作。Other PHP frameworks whose lifecycle start in the root directory can work without manual configuration of the virtual application path.

在 Windows 终端中,使用 az resource update 命令设置虚拟应用程序路径。In the windows terminal, set the virtual application path by using the az resource update command. 替换 <appname> 占位符。Replace the <appname> placeholder.

az resource update --name web --resource-group myResourceGroup --namespace Microsoft.Web --resource-type config --parent sites/<app_name> --set properties.virtualApplications[0].physicalPath="site\wwwroot\public" --api-version 2015-06-01

默认情况下,Azure 应用服务将根虚拟应用程序路径 (/) 指向已部署的应用程序的文件的根目录 (sites\wwwroot)。By default, Azure App Service points the root virtual application path (/) to the root directory of the deployed application files (sites\wwwroot).

从 Git 推送到 AzurePush to Azure from Git

回到本地终端窗口,将 Azure 远程功能添加到本地 Git 存储库。Back in the local terminal window, add an Azure remote to your local Git repository. <deploymentLocalGitUrl-from-create-step> 替换为从创建 Web 应用保存的 Git 远程 URL。Replace <deploymentLocalGitUrl-from-create-step> with the URL of the Git remote that you saved from Create a web app.

git remote add azure <deploymentLocalGitUrl-from-create-step>

使用以下命令推送到 Azure 远程库以部署应用。Push to the Azure remote to deploy your app with the following command. 当 Git 凭据管理器提示输入凭据时,请确保输入在配置部署用户中创建的凭据,而不是用于登录到 Azure 门户的凭据。When Git Credential Manager prompts you for credentials, make sure you enter the credentials you created in Configure a deployment user, not the credentials you use to sign in to the Azure portal.

git push azure master

此命令可能需要花费几分钟时间运行。This command may take a few minutes to run. 运行时,该命令会显示类似于以下示例的信息:While running, it displays information similar to the following example:

Counting objects: 3, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 291 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Updating branch 'master'.
remote: Updating submodules.
remote: Preparing deployment for commit id 'a5e076db9c'.
remote: Running custom deployment command...
remote: Running deployment command...
...
< Output has been truncated for readability >

备注

你可能会发现,部署过程在即将结束时会安装 Composer 包。You may notice that the deployment process installs Composer packages at the end. 应用服务在默认部署期间不会运行这些自动化任务,因此该示例存储库的根目录中提供了两个附加的文件用于运行这些任务:App Service does not run these automations during default deployment, so this sample repository has three additional files in its root directory to enable it:

  • .deployment - 此文件告知应用服务要以自定义部署脚本的形式运行 bash deploy.sh.deployment - This file tells App Service to run bash deploy.sh as the custom deployment script.
  • deploy.sh - 自定义部署脚本。deploy.sh - The custom deployment script. 查看该文件时可以看到,它会先运行 npm install,再运行 php composer.phar installIf you review the file, you will see that it runs php composer.phar install after npm install.
  • composer.phar - Composer 包管理器。composer.phar - The Composer package manager.

可使用此方法将任何步骤添加到应用服务中的基于 Git 的部署。You can use this approach to add any step to your Git-based deployment to App Service. 有关详细信息,请参阅自定义部署脚本For more information, see Custom Deployment Script.

转到 Azure 应用Browse to the Azure app

浏览到 http://<app_name>.chinacloudsites.cn 并在列表中添加一些任务。Browse to http://<app_name>.chinacloudsites.cn and add a few tasks to the list.

在 Azure 应用服务中运行的 PHP 应用

恭喜,你的数据驱动的 PHP 应用正在 Azure 应用服务中运行。Congratulations, you're running a data-driven PHP app in Azure App Service.

在本地更新模型和重新部署Update model locally and redeploy

在此步骤中,对 task 数据模型和 webapp 进行简单更改,然后将更新发布到 Azure。In this step, you make a simple change to the task data model and the webapp, and then publish the update to Azure.

对于任务方案,需要修改应用程序,以便能够将任务标记为已完成。For the tasks scenario, you modify the application so that you can mark a task as complete.

添加列Add a column

在本地终端窗口中,导航到 Git 存储库中的根路径。In the local terminal window, navigate to the root of the Git repository.

tasks 表创建新数据库迁移:Generate a new database migration for the tasks table:

php artisan make:migration add_complete_column --table=tasks

此命令显示已生成的迁移文件的名称。This command shows you the name of the migration file that's generated. 在 database/migrations 中找到此文件,并打开它。Find this file in database/migrations and open it.

up 方法替换为以下代码:Replace the up method with the following code:

public function up()
{
    Schema::table('tasks', function (Blueprint $table) {
        $table->boolean('complete')->default(False);
    });
}

上述代码在名为 completetasks 表中添加一个布尔值列。The preceding code adds a boolean column in the tasks table called complete.

请将 down 方法替换为以下回滚操作代码:Replace the down method with the following code for the rollback action:

public function down()
{
    Schema::table('tasks', function (Blueprint $table) {
        $table->dropColumn('complete');
    });
}

在本地终端窗口中运行 Laravel 数据库迁移,以便在本地数据库中进行更改。In the local terminal window, run Laravel database migrations to make the change in the local database.

php artisan migrate

根据 Laravel 命名约定,模型 Task(请参阅 app/Task.php)默认映射到 tasks 表。Based on the Laravel naming convention, the model Task (see app/Task.php) maps to the tasks table by default.

更新应用程序逻辑Update application logic

打开 routes/web.php 文件。Open the routes/web.php file. 应用程序在此处定义其路由和业务逻辑。The application defines its routes and business logic here.

在文件末尾,添加包含以下代码的路由:At the end of the file, add a route with the following code:

/**
 * Toggle Task completeness
 */
Route::post('/task/{id}', function ($id) {
    error_log('INFO: post /task/'.$id);
    $task = Task::findOrFail($id);

    $task->complete = !$task->complete;
    $task->save();

    return redirect('/');
});

上述代码通过切换 complete 的值对数据模型进行简单的更新。The preceding code makes a simple update to the data model by toggling the value of complete.

更新视图Update the view

打开 resources/views/tasks.blade.php 文件。Open the resources/views/tasks.blade.php file. 搜索 <tr> 开始标记并将其替换为:Search for the <tr> opening tag and replace it with:

<tr class="{{ $task->complete ? 'success' : 'active' }}" >

上述代码会根据任务是否已完成来更改行的颜色。The preceding code changes the row color depending on whether the task is complete.

在下一行中包含以下代码:In the next line, you have the following code:

<td class="table-text"><div>{{ $task->name }}</div></td>

请将整行替换为以下代码:Replace the entire line with the following code:

<td>
    <form action="{{ url('task/'.$task->id) }}" method="POST">
        {{ csrf_field() }}

        <button type="submit" class="btn btn-xs">
            <i class="fa {{$task->complete ? 'fa-check-square-o' : 'fa-square-o'}}"></i>
        </button>
        {{ $task->name }}
    </form>
</td>

上述代码添加引用前面定义的路由的提交按钮。The preceding code adds the submit button that references the route that you defined earlier.

在本地测试更改Test the changes locally

在本地终端窗口中,从 Git 存储库的根目录运行开发服务器。In the local terminal window, run the development server from the root directory of the Git repository.

php artisan serve

若要查看任务状态更改,请导航至 http://localhost:8000 并选择复选框。To see the task status change, navigate to http://localhost:8000 and select the checkbox.

将复选框添加到任务

在终端键入 Ctrl + C 可停止 PHP。To stop PHP, type Ctrl + C in the terminal.

发布对 Azure 所做的更改Publish changes to Azure

在本地终端窗口中,使用生产连接字符串运行 Laravel 数据库迁移,在 Azure 数据库中进行更改。In the local terminal window, run Laravel database migrations with the production connection string to make the change in the Azure database.

php artisan migrate --env=production --force

提交在 Git 中进行的所有更改,然后将代码更改推送到 Azure。Commit all the changes in Git, and then push the code changes to Azure.

git add .
git commit -m "added complete checkbox"
git push azure master

git push 完成后,请导航至 Azure 应用,测试新功能。Once the git push is complete, navigate to the Azure app and test the new functionality.

发布到 Azure 的模型和数据库更改

如果添加任何任务,则它们保留在数据库中。If you added any tasks, they are retained in the database. 更新数据架构不会改变现有数据。Updates to the data schema leave existing data intact.

流式传输诊断日志Stream diagnostic logs

当 PHP 应用程序在 Azure 应用服务中运行时,可以将控制台日志通过管道传输到终端。While the PHP application runs in Azure App Service, you can get the console logs piped to your terminal. 这样可以获得相同的诊断消息,以帮助调试应用程序错误。That way, you can get the same diagnostic messages to help you debug application errors.

若要启动日志流式处理,请在 Azure CLI 中使用 az webapp log tail 命令。To start log streaming, use the az webapp log tail command in Azure CLI.

az webapp log tail --name <app_name> --resource-group myResourceGroup

启动日志流式处理后,请在浏览器中刷新 Azure 应用,以获取一些 Web 流量。Once log streaming has started, refresh the Azure app in the browser to get some web traffic. 现在可以看到通过管道传送到终端的控制台日志。You can now see console logs piped to the terminal. 如果没有立即看到控制台日志,请在 30 秒后重新查看。If you don't see console logs immediately, check again in 30 seconds.

若要随时停止日志流式处理,请键入 Ctrl+CTo stop log streaming at anytime, type Ctrl+C.

提示

PHP 应用程序可以使用标准 error_log() 输出到控制台。A PHP application can use the standard error_log() to output to the console. 示例应用程序在 app/Http/routes.php 中使用此方法。The sample application uses this approach in app/Http/routes.php.

作为一种 Web 框架,Laravel 使用 Monolog 作为日志记录提供程序。As a web framework, Laravel uses Monolog as the logging provider. 若要了解如何使用 Monolog 将消息输出到控制台,请参阅 PHP:如何使用 monolog 记录到控制台 (php://out)To see how to get Monolog to output messages to the console, see PHP: How to use monolog to log to console (php://out).

管理 Azure 应用Manage the Azure app

转到 Azure 门户管理已创建的应用。Go to the Azure portal to manage the app you created.

在左侧菜单中单击应用程序服务,然后单击 Azure 应用的名称。From the left menu, click App Services, and then click the name of your Azure app.

在门户中导航到 Azure 应用

这里我们可以看到应用的“概述”页。You see your app's Overview page. 在此处可以执行基本的管理任务,例如停止、启动、重启、浏览和删除。Here, you can perform basic management tasks like stop, start, restart, browse, and delete.

左侧菜单提供用于配置应用的页面。The left menu provides pages for configuring your app.

Azure 门户中的“应用服务”页

清理资源Clean up resources

若要清理资源,请运行以下命令:To clean up your resources, run the following command:

az group delete --name myResourceGroup

后续步骤Next steps

在本教程中,你已学习了如何执行以下操作:In this tutorial, you learned how to:

  • 在 Azure 中创建 MySQL 数据库Create a MySQL database in Azure
  • 将 PHP 应用连接到 MySQLConnect a PHP app to MySQL
  • 将应用部署到 AzureDeploy the app to Azure
  • 更新数据模型并重新部署应用Update the data model and redeploy the app
  • 从 Azure 流式传输诊断日志Stream diagnostic logs from Azure
  • 在 Azure 门户中管理应用Manage the app in the Azure portal

转到下一教程,了解如何向应用映射自定义 DNS 名称。Advance to the next tutorial to learn how to map a custom DNS name to the app.