你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
教程:使用 PostgreSQL 服务进行开发
Azure 容器应用允许连接到开发和生产级服务,为应用程序提供各种功能。
本教程介绍如何将开发 PostgreSQL 服务与容器应用配合使用。
本教程重点介绍了 Azure CLI 命令和 Bicep 模板片段。 如果使用 Bicep,可以将所有片段添加到单个 Bicep 文件,并一次性部署所有模板。
- 创建容器应用环境以部署服务和容器应用
- 创建 PostgreSQL 服务
- 创建并使用命令行应用以使用开发 PostgreSQL 服务
- 创建 pgweb 应用
- 将数据写入 PostgreSQL 数据库
先决条件
注意
对于单命令部署,请跳到最后一个azd
模板步骤。
设置
为通用值定义变量。
RESOURCE_GROUP="postgres-dev"
LOCATION="northcentralus"
ENVIRONMENT="aca-env"
PG_SVC="postgres01"
PSQL_CLI_APP="psql-cloud-cli-app"
以下变量允许使用 CLI 部署 Bicep 模板。
RESOURCE_GROUP="postgres-dev"
LOCATION="northcentralus"
对于 Bicep,首先创建名为 postgres-dev.bicep
的文件,然后添加具有以下默认值的参数。
targetScope = 'resourceGroup'
param location string = resourceGroup().location
param appEnvironmentName string = 'aca-env'
param pgSvcName string = 'postgres01'
param pgsqlCliAppName string = 'psql-cloud-cli-app'
在任何阶段部署 bicep 模板时,都可以使用 az deployment group create
命令。
az deployment group create -g $RESOURCE_GROUP \
--query 'properties.outputs.*.value' \
--template-file postgres-dev.bicep
定义初始变量。
AZURE_ENV_NAME="azd-postgres-dev"
LOCATION="northcentralus"
使用这些值初始化最小 azd
模板。
azd init \
--environment "$AZURE_ENV_NAME" \
--location "$LOCATION" \
--no-prompt
备注
AZURE_ENV_NAME
不同于容器应用环境名称。 在此上下文中,azd
中的 AZURE_ENV_NAME
适用于模板中的所有资源。 这些资源包括与容器应用不关联的资源。 你要为容器应用环境创建不同的名称。
接下来,创建 infra/main.bicep
并定义参数供以后使用。
param appEnvironmentName string = 'aca-env'
param pgSvcName string = 'postgres01'
param pgsqlCliAppName string = 'psql-cloud-cli-app'
登录 Azure。
az login
将 CLI 升级到最新版本。
az upgrade
将 Bicep 升级到最新版本。
az bicep upgrade
添加 containerapp
扩展。
az extension add --name containerapp --upgrade
注册所需的命名空间。
az provider register --namespace Microsoft.App
az provider register --namespace Microsoft.OperationalInsights
创建容器应用环境
创建资源组。
az group create \
--name "$RESOURCE_GROUP" \
--location "$LOCATION"
az group create \
--name "$RESOURCE_GROUP" \
--location "$LOCATION"
在任何阶段部署 bicep 模板时,都可以使用 az deployment group create
命令。
az deployment group create -g $RESOURCE_GROUP \
--query 'properties.outputs.*.value' \
--template-file postgres-dev.bicep
在 azd
中管理资源组不需要特殊设置。 azd
命令从 AZURE_ENV_NAME
/--environment
值获取资源组。
可以使用 up
命令测试最小模板。
azd up
运行此命令会创建一个空资源组。
创建容器应用环境。
az containerapp env create \
--name "$ENVIRONMENT" \
--resource-group "$RESOURCE_GROUP" \
--location "$LOCATION"
向 postgres-dev.bicep
文件添加以下值。
resource appEnvironment 'Microsoft.App/managedEnvironments@2023-04-01-preview' = {
name: appEnvironmentName
location: location
properties: {
appLogsConfiguration: {
destination: 'azure-monitor'
}
}
}
Azure CLI 会自动为每个环境创建一个 Log Analytics 工作区。 若要使用 Bicep 模板生成工作区,请显式声明环境并在模板中链接到该环境。 此步骤使部署更加稳定,即使代价是有点冗长。
向你的环境添加以下值。
resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {
name: '${appEnvironmentName}-log-analytics'
location: location
properties: {
sku: {
name: 'PerGB2018'
}
}
}
resource appEnvironment 'Microsoft.App/managedEnvironments@2023-04-01-preview' = {
name: appEnvironmentName
location: location
properties: {
appLogsConfiguration: {
destination: 'log-analytics'
logAnalyticsConfiguration: {
customerId: logAnalytics.properties.customerId
sharedKey: logAnalytics.listKeys().primarySharedKey
}
}
}
}
azd
所用的模版使用 bicep 模块。
创建名为 ./infra/core/host
的文件夹,然后创建包含以下内容的 ./infra/core/host/container-apps-environment.bicep
模块。
param name string
param location string = resourceGroup().location
param tags object = {}
resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {
name: '${name}-log-analytics'
location: location
tags: tags
properties: {
sku: {
name: 'PerGB2018'
}
}
}
resource appEnvironment 'Microsoft.App/managedEnvironments@2023-04-01-preview' = {
name: name
location: location
tags: tags
properties: {
appLogsConfiguration: {
destination: 'log-analytics'
logAnalyticsConfiguration: {
customerId: logAnalytics.properties.customerId
sharedKey: logAnalytics.listKeys().primarySharedKey
}
}
}
}
output appEnvironmentId string = appEnvironment.id
在 ./infra/main.bicep
文件中,使用以下值加载模块。
module appEnvironment './core/host/container-apps-environment.bicep' = {
name: 'appEnvironment'
scope: rg
params: {
name: appEnvironmentName
location: location
tags: tags
}
}
运行 azd up
部署模板。
创建 PostgreSQL 服务
创建 PostgreSQL 服务。
az containerapp add-on postgres create \
--name "$PG_SVC" \
--resource-group "$RESOURCE_GROUP" \
--environment "$ENVIRONMENT"
将以下值添加到 postgres-dev.bicep
。
resource postgres 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: pgSvcName
location: location
properties: {
environmentId: appEnvironment.id
configuration: {
service: {
type: 'postgres'
}
}
}
}
output postgresLogs string = 'az containerapp logs show -n ${postgres.name} -g ${resourceGroup().name} --follow --tail 30'
若要部署 bicep 模板,请运行 az deployment group create
。
az deployment group create -g $RESOURCE_GROUP \
--query 'properties.outputs.*.value' \
--template-file postgres-dev.bicep
输出 postgresLogs
命令会输出一个 CLI 命令,你可以在部署后运行它以查看 PostgreSQL 日志。
可以运行该命令来查看新 postgres 服务的初始化日志。
创建包含以下内容的 ./infra/core/host/container-app-service.bicep
模块文件。
param name string
param location string = resourceGroup().location
param tags object = {}
param environmentId string
param serviceType string
resource service 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: name
location: location
tags: tags
properties: {
environmentId: environmentId
configuration: {
service: {
type: serviceType
}
}
}
}
output serviceId string = service.id
接下来,使用以下声明更新 ./infra/main.bicep
模块文件。
module postgres './core/host/container-app-service.bicep' = {
name: 'postgres'
scope: rg
params: {
name: pgSvcName
location: location
tags: tags
environmentId: appEnvironment.outputs.appEnvironmentId
serviceType: 'postgres'
}
}
然后使用 azd up
部署模板。
`azd up`
查看 Postgres 实例的日志输出
使用 logs
命令查看日志消息。
az containerapp logs show \
--name $PG_SVC \
--resource-group $RESOURCE_GROUP \
--follow --tail 30
上一个 bicep 示例包含用于查看日志的命令输出。
例如:
[
"az containerapp logs show -n postgres01 -g postgres-dev --follow --tail 30"
]
如果没有该命令,则可以通过 CLI 使用服务名称查看日志。
az containerapp logs show \
--name $PG_SVC \
--resource-group $RESOURCE_GROUP \
--follow --tail 30
使用日志命令查看日志
az containerapp logs show \
--name postgres01 \
--resource-group $RESOURCE_GROUP \
--follow --tail 30
创建应用以测试服务
创建应用时,先创建一个调试应用,以使用 psql
CLI 连接到 PostgreSQL 实例。
创建绑定到 PostgreSQL 服务的 psql
应用。
az containerapp create \
--name "$PSQL_CLI_APP" \
--image mcr.microsoft.com/k8se/services/postgres:14 \
--bind "$PG_SVC" \
--environment "$ENVIRONMENT" \
--resource-group "$RESOURCE_GROUP" \
--min-replicas 1 \
--max-replicas 1 \
--command "/bin/sleep" "infinity"
将以下值添加到 postgres-dev.bicep
。
resource pgsqlCli 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: pgsqlCliAppName
location: location
properties: {
environmentId: appEnvironment.id
template: {
serviceBinds: [
{
serviceId: postgres.id
}
]
containers: [
{
name: 'psql'
image: 'mcr.microsoft.com/k8se/services/postgres:14'
command: [ '/bin/sleep', 'infinity' ]
}
]
scale: {
minReplicas: 1
maxReplicas: 1
}
}
}
}
output pgsqlCliExec string = 'az containerapp exec -n ${pgsqlCli.name} -g ${resourceGroup().name} --revision ${pgsqlCli.properties.latestRevisionName} --command /bin/bash'
提示
输出 pgsqlCliExec
会输出一个 CLI 命令,以在部署后执行到测试应用中。
在 ./infra/core/host/container-app.bicep
下创建模块,并添加以下值。
param name string
param location string = resourceGroup().location
param tags object = {}
param environmentId string
param serviceId string = ''
param containerName string
param containerImage string
param containerCommands array = []
param containerArgs array = []
param minReplicas int
param maxReplicas int
param targetPort int = 0
param externalIngress bool = false
resource app 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: name
location: location
tags: tags
properties: {
environmentId: environmentId
configuration: {
ingress: targetPort > 0 ? {
targetPort: targetPort
external: externalIngress
} : null
}
template: {
serviceBinds: !empty(serviceId) ? [
{
serviceId: serviceId
}
] : null
containers: [
{
name: containerName
image: containerImage
command: !empty(containerCommands) ? containerCommands : null
args: !empty(containerArgs) ? containerArgs : null
}
]
scale: {
minReplicas: minReplicas
maxReplicas: maxReplicas
}
}
}
}
现在,通过添加以下值在 ./infra/main.bicep
中使用该模块。
module psqlCli './core/host/container-app.bicep' = {
name: 'psqlCli'
scope: rg
params: {
name: pgsqlCliAppName
location: location
tags: tags
environmentId: appEnvironment.outputs.appEnvironmentId
serviceId: postgres.outputs.serviceId
containerImage: 'mcr.microsoft.com/k8se/services/postgres:14'
containerName: 'psql'
maxReplicas: 1
minReplicas: 1
containerCommands: [ '/bin/sleep', 'infinity' ]
}
}
使用 azd up
部署模板。
azd up
运行 CLI exec
命令以连接到测试应用。
az containerapp exec \
--name $PSQL_CLI_APP \
--resource-group $RESOURCE_GROUP \
--command /bin/bash
前面的 Bicep 示例包含向你展示如何运行应用的输出。
例如:
[
"az containerapp logs show -n postgres01 -g postgres-dev --follow --tail 30",
"az containerapp exec -n psql-cloud-cli-app -g postgres-dev --command /bin/bash"
]
如果没有该命令,则可以通过 exec
命令使用应用名称运行应用程序。
az containerapp exec \
--name $PSQL_CLI_APP \
--resource-group $RESOURCE_GROUP \
--command /bin/bash
az containerapp exec \
--name psql-cloud-cli-app \
--resource-group $RESOURCE_GROUP \
--command /bin/bash
对测试应用使用 --bind
或 serviceBinds
时,连接信息会注入到应用程序环境中。 连接到测试容器后,可以使用 env
命令检查值。
env | grep "^POSTGRES_"
POSTGRES_HOST=postgres01
POSTGRES_PASSWORD=AiSf...
POSTGRES_SSL=disable
POSTGRES_URL=postgres://postgres:AiSf...@postgres01:5432/postgres?sslmode=disable
POSTGRES_DATABASE=postgres
POSTGRES_PORT=5432
POSTGRES_USERNAME=postgres
POSTGRES_CONNECTION_STRING=host=postgres01 database=postgres user=postgres password=AiSf...
使用 psql
连接到服务
psql $POSTGRES_URL
创建名为 accounts
的表并插入数据。
postgres=# CREATE TABLE accounts (
user_id serial PRIMARY KEY,
username VARCHAR ( 50 ) UNIQUE NOT NULL,
email VARCHAR ( 255 ) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
last_login TIMESTAMP
);
postgres=# INSERT INTO accounts (username, email, created_on)
VALUES
('user1', 'user1@example.com', current_timestamp),
('user2', 'user2@example.com', current_timestamp),
('user3', 'user3@example.com', current_timestamp);
postgres=# SELECT * FROM accounts;
将开发服务与现有应用配合使用
如果已有使用 PostgreSQL 的应用,可以更改加载连接信息的方式。
首先,创建以下环境变量。
POSTGRES_HOST=postgres01
POSTGRES_PASSWORD=AiSf...
POSTGRES_SSL=disable
POSTGRES_URL=postgres://postgres:AiSf...@postgres01:5432/postgres?sslmode=disable
POSTGRES_DATABASE=postgres
POSTGRES_PORT=5432
POSTGRES_USERNAME=postgres
POSTGRES_CONNECTION_STRING=host=postgres01 database=postgres user=postgres password=AiSf...
借助 CLI(或 Bicep),可以更新应用,添加 --bind $PG_SVC
以使用开发服务。
绑定到开发服务
部署 pgweb 以查看和管理 PostgreSQL 实例。
resource pgweb 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: 'pgweb'
location: location
properties: {
environmentId: appEnvironment.id
configuration: {
ingress: {
external: true
targetPort: 8081
}
}
template: {
serviceBinds: [
{
serviceId: postgres.id
name: 'postgres'
}
]
containers: [
{
name: 'pgweb'
image: 'docker.io/sosedoff/pgweb:latest'
command: [
'/bin/sh'
]
args: [
'-c'
'PGWEB_DATABASE_URL=$POSTGRES_URL /usr/bin/pgweb --bind=0.0.0.0 --listen=8081'
]
}
]
}
}
}
output pgwebUrl string = 'https://${pgweb.properties.configuration.ingress.fqdn}'
使用相同的命令部署 bicep 模板。
az deployment group create -g $RESOURCE_GROUP \
--query 'properties.outputs.*.value' \
--template-file postgres-dev.bicep
Bicep 命令会返回一个 URL。 将此 URL 复制到浏览器以访问部署的站点。
使用以下值更新 ./infra/main.bicep
。
module pgweb './core/host/container-app.bicep' = {
name: 'pgweb'
scope: rg
params: {
name: 'pgweb'
location: location
tags: tags
environmentId: appEnvironment.outputs.appEnvironmentId
serviceId: postgres.outputs.serviceId
containerImage: 'docker.io/sosedoff/pgweb:latest'
containerName: 'pgweb'
maxReplicas: 1
minReplicas: 1
containerCommands: [ '/bin/sh' ]
containerArgs: [
'-c'
'PGWEB_DATABASE_URL=$POSTGRES_URL /usr/bin/pgweb --bind=0.0.0.0 --listen=8081'
]
targetPort: 8081
externalIngress: true
}
}
使用 azd up
部署模板。
azd up
部署所有资源
如果要一次性部署所有资源,请使用以下示例。
Bicep
以下 Bicep 模板包含本教程中使用的所有资源。
可以创建包含此内容的 postgres-dev.bicep
文件。
targetScope = 'resourceGroup'
param location string = resourceGroup().location
param appEnvironmentName string = 'aca-env'
param pgSvcName string = 'postgres01'
param pgsqlCliAppName string = 'psql-cloud-cli-app'
resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {
name: '${appEnvironmentName}-log-analytics'
location: location
properties: {
sku: {
name: 'PerGB2018'
}
}
}
resource appEnvironment 'Microsoft.App/managedEnvironments@2023-04-01-preview' = {
name: appEnvironmentName
location: location
properties: {
appLogsConfiguration: {
destination: 'log-analytics'
logAnalyticsConfiguration: {
customerId: logAnalytics.properties.customerId
sharedKey: logAnalytics.listKeys().primarySharedKey
}
}
}
}
resource postgres 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: pgSvcName
location: location
properties: {
environmentId: appEnvironment.id
configuration: {
service: {
type: 'postgres'
}
}
}
}
resource pgsqlCli 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: pgsqlCliAppName
location: location
properties: {
environmentId: appEnvironment.id
template: {
serviceBinds: [
{
serviceId: postgres.id
}
]
containers: [
{
name: 'psql'
image: 'mcr.microsoft.com/k8se/services/postgres:14'
command: [ '/bin/sleep', 'infinity' ]
}
]
scale: {
minReplicas: 1
maxReplicas: 1
}
}
}
}
resource pgweb 'Microsoft.App/containerApps@2023-04-01-preview' = {
name: 'pgweb'
location: location
properties: {
environmentId: appEnvironment.id
configuration: {
ingress: {
external: true
targetPort: 8081
}
}
template: {
serviceBinds: [
{
serviceId: postgres.id
name: 'postgres'
}
]
containers: [
{
name: 'pgweb'
image: 'docker.io/sosedoff/pgweb:latest'
command: [
'/bin/sh'
]
args: [
'-c'
'PGWEB_DATABASE_URL=$POSTGRES_URL /usr/bin/pgweb --bind=0.0.0.0 --listen=8081'
]
}
]
}
}
}
output pgsqlCliExec string = 'az containerapp exec -n ${pgsqlCli.name} -g ${resourceGroup().name} --revision ${pgsqlCli.properties.latestRevisionName} --command /bin/bash'
output postgresLogs string = 'az containerapp logs show -n ${postgres.name} -g ${resourceGroup().name} --follow --tail 30'
output pgwebUrl string = 'https://${pgweb.properties.configuration.ingress.fqdn}'
使用 Azure CLI 部署模板。
RESOURCE_GROUP="postgres-dev"
LOCATION="northcentralus"
az group create \
--name "$RESOURCE_GROUP" \
--location "$LOCATION"
az deployment group create -g $RESOURCE_GROUP \
--query 'properties.outputs.*.value' \
--template-file postgres-dev.bicep
Azure 开发人员 CLI
GitHub 上提供了一个最终模板。
使用 azd up
部署模板。
git clone https://github.com/Azure-Samples/aca-dev-service-postgres-azd
cd aca-dev-service-postgres-azd
azd up
清理资源
完成后,运行以下命令以删除包含容器应用资源的资源组。
注意
以下命令删除指定的资源组及其包含的所有资源。 如果指定的资源组中存在本教程范围外的资源,这些资源也会被删除。
az group delete \
--resource-group $RESOURCE_GROUP