php 管理mysql 应用,教程:将 PHP 应用与 MySQL 配合使用 - Azure App Service | Microsoft Docs...

您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:在 Azure 应用服务中生成 PHP 和 MySQL 应用Tutorial: Build a PHP and MySQL app in Azure App Service

06/15/2020

本文内容

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

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

5c924379a675120d33a25b6b25f26b60.png

在本教程中,你将了解如何执行以下操作: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 free account before you begin.

先决条件Prerequisites

完成本教程:To complete this tutorial:

启用 Laravel 所需的以下 PHP 扩展:OpenSSL、PDO-MySQL、Mbstring、Tokenizer、XMLEnable the following PHP extensions Laravel needs: OpenSSL, PDO-MySQL, Mbstring, Tokenizer, XML

安装并启动 MySQL

- Use the Bash environment in Azure Cloud Shell.b539b034fc472a2347bf7d1948550896.pngb539b034fc472a2347bf7d1948550896.png

- 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。If you prefer, install the Azure CLI to run CLI reference commands.- 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。If you're using a local installation, sign in to the Azure CLI by using the az login command. 若要完成身份验证过程,请遵循终端中显示的步骤。To finish the authentication process, follow the steps displayed in your terminal. 有关其他登录选项,请参阅登录 Azure CLI。For additional sign-in options, see Sign in with the Azure CLI.- 出现提示时,请在首次使用时安装 Azure CLI 扩展。When you're prompted, install Azure CLI extensions on first use. For more information about extensions, see Use extensions with the Azure CLI.

- 运行 az version 以查找安装的版本和依赖库。Run az version to find the version and dependent libraries that are installed. 若要升级到最新版本,请运行 az upgrade。To upgrade to the latest version, run az upgrade.Install and start MySQL

- Use the Bash environment in Azure Cloud Shell.b539b034fc472a2347bf7d1948550896.pngb539b034fc472a2347bf7d1948550896.png

- 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。If you prefer, install the Azure CLI to run CLI reference commands.- 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。If you're using a local installation, sign in to the Azure CLI by using the az login command. 若要完成身份验证过程,请遵循终端中显示的步骤。To finish the authentication process, follow the steps displayed in your terminal. 有关其他登录选项,请参阅登录 Azure CLI。For additional sign-in options, see Sign in with the Azure CLI.- 出现提示时,请在首次使用时安装 Azure CLI 扩展。When you're prompted, install Azure CLI extensions on first use. For more information about extensions, see Use extensions with the Azure CLI.

- 运行 az version 以查找安装的版本和依赖库。Run az version to find the version and dependent libraries that are installed. 若要升级到最新版本,请运行 az upgrade。To upgrade to the latest version, run az upgrade.

准备本地 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 file named .env. 复制下列变量到 .env 文件。Copy the following variables into the .env file. 请将 占位符替换为 MySQL 根用户的密码。Replace the 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=

有关 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:8000。Navigate to http://localhost:8000 in a browser. 在页面中添加一些任务。Add a few tasks in the page.

835faa1dfd4eec596c6272c705c42073.png

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

在 Azure 中创建 MySQLCreate MySQL in Azure

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, such as 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.

在 Cloud Shell 中,使用 az group create 命令创建资源组。In the Cloud Shell, create a resource group with the az group create command. 以下示例在“西欧”位置创建名为“myResourceGroup”的资源组。The following example creates a resource group named myResourceGroup in the West Europe location. 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 "West Europe"

通常在附近的区域中创建资源组和资源。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

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

在下列命令中,用唯一的服务器名称替换 占位符,用用户名替换 占位符,并用密码替换 占位符 。In the following command, substitute a unique server name for the placeholder, a user name for the , and a password for the placeholder. 此服务器名称用作 MySQL 终结点 (https://.mysql.database.azure.com) 的一部分,因此需在 Azure 的所有服务器中保持唯一。The server name is used as part of your MySQL endpoint (https://.mysql.database.azure.com), so the name needs to be unique across all servers in Azure. 有关选择 MySQL DB SKU 的详细信息,请参阅为 MySQL 服务器创建 Azure 数据库。For details on selecting MySQL DB SKU, see Create an Azure Database for MySQL server.

az mysql server create --resource-group myResourceGroup --name --location "West Europe" --admin-user --admin-password --sku-name B_Gen5_1

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

{

"administratorLogin": "",

"administratorLoginPassword": null,

"fullyQualifiedDomainName": ".mysql.database.azure.com",

"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/",

"location": "westeurope",

"name": "",

"resourceGroup": "myResourceGroup",

...

- < Output has been truncated for readability >

}

配置服务器防火墙Configure server firewall

在 Cloud Shell 中,使用 az mysql server firewall-rule create 命令创建 MySQL 服务器的防火墙规则,以便建立客户端连接。In the Cloud Shell, 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 --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.

在 Cloud Shell 中再次运行该命令(将 替换为本地 IPv4 IP 地址),以便从本地计算机进行访问。In the Cloud Shell, run the command again to allow access from your local computer by replacing with your local IPv4 IP address.

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

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

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

mysql -u @ -h .mysql.database.azure.com -P 3306 -p

创建生产数据库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 作为密码。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_HOST 和 DB_USERNAME 中的占位符 。Replace the placeholder__ in both DB_HOST and DB_USERNAME.

APP_ENV=production

APP_DEBUG=true

APP_KEY=

DB_CONNECTION=mysql

DB_HOST=.mysql.database.azure.com

DB_DATABASE=sampledb

DB_USERNAME=phpappuser@

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. To connect to your MySQL database in Azure, you must use the .pem certificate supplied by Azure Database for MySQL.

打开 config/database.php,将 sslmode 和 options 参数添加到 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',

] : []

],

'mysql' => [

...

'sslmode' => env('DB_SSLMODE', 'prefer'),

'options' => (env('MYSQL_SSL') && extension_loaded('pdo_mysql')) ? [

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:8000。Navigate 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.

835faa1dfd4eec596c6272c705c42073.png

在终端键入 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

可以使用“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. 将 和 替换为部署用户的用户名和密码。Replace and 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 --password

JSON 输出会将该密码显示为 null。The 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

在 Cloud Shell 中,使用 az appservice plan create 命令创建一个应用服务计划。In the Cloud Shell, 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": "West Europe",

"hostingEnvironmentProfile": null,

"id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",

"kind": "app",

"location": "West Europe",

"maximumNumberOfWorkers": 1,

"name": "myAppServicePlan",

< JSON data removed for brevity. >

"targetWorkerSizeId": 0,

"type": "Microsoft.Web/serverfarms",

"workerTierName": null

}

在 Cloud Shell 中,使用 az appservice plan create 命令在资源组中创建应用服务计划。In the Cloud Shell, create an App Service plan in the resource group with the az appservice plan create command.

以下示例在 免费 定价层 (--sku F1) 和 Linux 容器 (--is-linux) 中创建名为 myAppServicePlan 的应用服务计划。The following example creates an App Service plan named myAppServicePlan in the Free pricing tier (--sku F1) and in a Linux container (--is-linux).

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku F1 --is-linux

创建应用服务计划后,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": "West Europe",

"hostingEnvironmentProfile": null,

"id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",

"kind": "linux",

"location": "West Europe",

"maximumNumberOfWorkers": 1,

"name": "myAppServicePlan",

"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.

在 Cloud Shell 中可以使用 az webapp create 命令。In the Cloud Shell, you can use the az webapp create command. 在以下示例中,将 替换为全局唯一的应用名称(有效字符是 a-z、0-9 和 -)。In the following example, replace with a globally unique app name (valid characters are a-z, 0-9, and -). 运行时设置为 PHP|7.2。The runtime is set to PHP|7.2. To see all supported runtimes, run az webapp list-runtimes --linux.

# Bash

az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name --runtime "PHP|7.2" --deployment-local-git

# PowerShell

az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name --runtime "PHP|7.2" --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://@.scm.azurewebsites.net/.git'

{

"availabilityState": "Normal",

"clientAffinityEnabled": true,

"clientCertEnabled": false,

"cloningInfo": null,

"containerSize": 0,

"dailyMemoryTimeQuota": 0,

"defaultHostName": ".azurewebsites.net",

"deploymentLocalGitUrl": "https://@.scm.azurewebsites.net/.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://@.scm.azurewebsites.net/.git。The URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://@.scm.azurewebsites.net/.git. 保存此 URL,后续将会用到。Save this URL as you need it later.

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

在 Cloud Shell 中可以使用 az webapp create 命令。In the Cloud Shell, you can use the az webapp create command. 在以下示例中,将 替换为全局唯一的应用名称(有效字符是 a-z、0-9 和 -)。In the following example, replace with a globally unique app name (valid characters are a-z, 0-9, and -). 运行时设置为 PHP|7.2。The runtime is set to PHP|7.2. To see all supported runtimes, run az webapp list-runtimes --linux.

# Bash

az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name --runtime "PHP|7.2" --deployment-local-git

# PowerShell

az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name --runtime "PHP|7.2" --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://@.scm.azurewebsites.net/.git'

{

"availabilityState": "Normal",

"clientAffinityEnabled": true,

"clientCertEnabled": false,

"cloningInfo": null,

"containerSize": 0,

"dailyMemoryTimeQuota": 0,

"defaultHostName": ".azurewebsites.net",

"deploymentLocalGitUrl": "https://@.scm.azurewebsites.net/.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://@.scm.azurewebsites.net/.git。The URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://@.scm.azurewebsites.net/.git. 保存此 URL,后续将会用到。Save this URL as you need it later.

配置数据库设置Configure database settings

In App Service, you set environment variables as app settings by using the az webapp config appsettings set command.

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

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

可以使用 PHP getenv 方法访问这些设置。You can use the PHP getenv method to access the settings. Laravel 代码使用 env 包装器,而不是 PHP getenv。the 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 生成新的应用程序密钥,但不要将它保存到 .env。In the local terminal window, use php artisan to generate a new application key without saving it to .env.

php artisan key:generate --show

在 Cloud Shell 中,使用 az webapp config appsettings set 命令在应用服务应用中设置应用程序密钥。In the Cloud Shell, set the application key in the App Service app by using the az webapp config appsettings set command. 替换占位符 和 。Replace the placeholders and .

az webapp config appsettings set --name --resource-group myResourceGroup --settings APP_KEY="" 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.

在 Cloud Shell 中,使用 az resource update 命令设置虚拟应用程序路径。In the Cloud Shell, set the virtual application path by using the az resource update command. 替换 占位符。Replace the placeholder.

az resource update --name web --resource-group myResourceGroup --namespace Microsoft.Web --resource-type config --parent sites/ --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).

Laravel 应用程序生命周期在 public 目录中开始,而不是在应用程序的根目录中开始。Laravel application lifecycle begins in the public directory instead of the application's root directory. 适用于应用服务的默认 PHP Docker 映像使用 Apache,不允许为 Laravel 自定义 DocumentRoot。The default PHP Docker image for App Service uses Apache, and it doesn't let you customize the DocumentRoot for Laravel. 但是,可以使用 .htaccess 来重写所有请求,使之指向 /public 而不是根目录。However, you can use .htaccess to rewrite all requests to point to /public instead of the root directory. 在存储库根目录中,已针对此目的添加了 .htaccess。In the repository root, an .htaccess is added already for this purpose. 有了它即可部署 Laravel 应用程序。With it, your Laravel application is ready to be deployed.

有关详细信息,请参阅更改站点根。For more information, see Change site root.

从 Git 推送到 AzurePush to Azure from Git

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

git remote add azure

使用以下命令推送到 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 main

此命令可能需要花费几分钟时间运行。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 'main'.

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 install。If 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 远程功能添加到本地 Git 存储库。Back in the local terminal window, add an Azure remote to your local Git repository. 将 替换为在创建 Web 应用中保存的 Git 远程 URL。Replace with the URL of the Git remote that you saved from Create a web app.

git remote add azure

使用以下命令推送到 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 main

此命令可能需要花费几分钟时间运行。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 'main'.

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 >

转到 Azure 应用Browse to the Azure app

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

adc74ee5e306bd30761915c71d5e3eb5.png

恭喜,你的数据驱动的 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);

});

}

上述代码在名为 complete 的 tasks 表中添加一个布尔值列。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. 找到

开始标记并将其替换为:Find the opening tag and replace it with:

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

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

{{ $task->name }}

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

{{ csrf_field() }}

{{ $task->name }}

上述代码添加引用前面定义的路由的提交按钮。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.

cde3785973e0262121da6648d3f61914.png

在终端键入 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 main

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

5c924379a675120d33a25b6b25f26b60.png

如果添加任何任务,则它们保留在数据库中。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.

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

az webapp log tail --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+C。To stop log streaming at any time, type Ctrl+C.

若要在应用服务中从应用程序代码内部访问生成的控制台日志,请在 Cloud Shell 中运行以下命令,打开诊断日志记录:To access the console logs generated from inside your application code in App Service, turn on diagnostics logging by running the following command in the Cloud Shell:

az webapp log config --resource-group --name --application-logging true --level Verbose

--level 的可能值为:Error、Warning、Info 和 Verbose。Possible values for --level are: Error, Warning, Info, and Verbose. 每个后续级别包括上一个级别。Each subsequent level includes the previous level. 例如:Error 仅包含错误消息,Verbose 则包含所有消息。For example: Error includes only error messages, and Verbose includes all messages.

启用诊断日志记录功能以后,请运行以下命令来查看日志流:Once diagnostic logging is turned on, run the following command to see the log stream:

az webapp log tail --resource-group --name

如果没有立即看到控制台日志,请在 30 秒后重新查看。If you don't see console logs immediately, check again in 30 seconds.

备注

也可通过浏览器在 https://.scm.azurewebsites.net/api/logs/docker 中检查日志文件。You can also inspect the log files from the browser at https://.scm.azurewebsites.net/api/logs/docker.

若要随时停止日志流式处理,请键入 Ctrl+C。To stop log streaming at any time, 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. 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.

33cc980dffb64f4842bac6aef63bcfba.png

这里我们可以看到应用的“概述”页。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.

32dadbf7c8999ff5098c69be33fd508a.png

清理资源Clean up resources

在前面的步骤中,你在资源组中创建了 Azure 资源。In the preceding steps, you created Azure resources in a resource group. 如果认为将来不需要这些资源,请在 Cloud Shell 中运行以下命令删除资源组:If you don't expect to need these resources in the future, delete the resource group by running the following command in the Cloud Shell:

az group delete --name myResourceGroup

此命令可能需要花费一点时间运行。This command may take a minute to run.

后续步骤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.

或者,查看其他资源:Or, check out other resources:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值