教學課程:使用 PostgreSQL 服務進行開發
Azure Container Apps 可讓您連線到開發和生產等級的服務,為您的應用程式提供各種不同的功能。
在本教學課程中,您將瞭解如何搭配 Container Apps 使用開發 PostgreSQL 服務。
本教學課程中提供 Azure CLI 命令和 Bicep 範本片段。 如果您使用 Bicep,您可以將所有片段新增至單一 Bicep 檔案,並 一次部署範本。
- 建立 Container Apps 環境以部署您的服務和容器應用程式
- 建立 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
不同于容器應用程式環境名稱。 在此內容中, AZURE_ENV_NAME
azd
會針對範本中的所有資源使用 。 這些資源包括未與容器應用程式相關聯的資源。 您會為 Container Apps 環境建立不同的名稱。
接下來,建立 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
建立 Container Apps 環境
建立資源群組。
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
執行此命令會建立空的資源群組。
建立 Container Apps 環境。
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
}
}
}
}
使用bicep 模組所使用的 azd
範本。
建立名為 ./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
使用 logs 命令來檢視記錄
az containerapp logs show \
--name postgres01 \
--resource-group $RESOURCE_GROUP \
--follow --tail 30
建立應用程式以測試服務
當您建立應用程式時,首先會建立偵錯應用程式以使用 psql
CLI 連線到 PostgreSQL 實例。
建立 psql
系結至 PostgreSQL 服務的應用程式。
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