Linux 및 PostgreSQL 워크로드 탐색 및 실행

완료됨

이 단원에서 학습할 내용은 다음과 같습니다.

  • Bicep 템플릿을 사용하여 Azure Blob Storage 계정을 배포합니다.
  • Blob Storage 컨테이너를 만듭니다.
  • 이미지를 Blob Storage 계정으로 마이그레이션합니다.
  • tailwind.sql을 Blob Storage 계정에 업로드합니다.
  • Azure CLI를 사용하여 Azure 가상 머신에 연결합니다.
  • 스토리지 계정에서 파일을 다운로드합니다.
  • psql을 사용하여 PostgreSQL 서버에 연결하고 SQL 파일을 가져옵니다.
  • 명령줄을 통해 애플리케이션을 대화형으로 실행합니다.
  • 애플리케이션이 올바르게 실행되는지 확인합니다.

deploy/vm-postgres.bicep를 사용하여 스토리지 계정을 배포합니다.

로컬 컴퓨터에서 다음 명령을 실행합니다.

az deployment group create \
    --resource-group 240900-linux-postgres \
    --template-file deploy/vm-postgres.bicep \
    --parameters \
        deployVm=false \
        deployPostgres=false \
        deployStorage=true

Storage Blob 데이터 소유자 역할에 현재 사용자 추가

STORAGE_ACCOUNT_ID=$(az storage account list \
    --resource-group 240900-linux-postgres \
    --query '[0].id' \
    -o tsv)

USER_ID=$(az ad signed-in-user show \
    --query id \
    -o tsv)

az role assignment create \
    --role "Storage Blob Data Owner" \
    --assignee $USER_ID \
    --scope $STORAGE_ACCOUNT_ID

스토리지 계정에 container1이라는 컨테이너 만들기

STORAGE_ACCOUNT_NAME=$(az storage account list \
    --resource-group 240900-linux-postgres \
    --query '[0].name' \
    -o tsv)

echo "STORAGE_ACCOUNT_NAME: $STORAGE_ACCOUNT_NAME"

az storage container create \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --name container1

이미지를 스토리지 계정의 하위 폴더로 마이그레이션

az storage blob upload-batch \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --overwrite \
    --destination container1/images \
    --source app/data/images

다음과 같은 출력이 표시됩니다.

[
  {
    "Blob": "https://storageji2dbe.blob.core.windows.net/container1/images/wrench_set.jpg",
    "Last Modified": "...",
    "Type": "image/jpeg",
    "eTag": "\"0x8DCE0CA938AF41B\""
  },
  {
    "Blob": "https://storageji2dbe.blob.core.windows.net/container1/images/planer.jpg",
    "Last Modified": "...",
    "Type": "image/jpeg",
    "eTag": "\"0x8DCE0CA939DF18B\""
  },
  ...
]

스토리지 계정에 app/data/postgres/tailwind.sql를 업로드

az storage blob upload \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --container-name container1 \
    --file app/data/postgres/tailwind.sql \
    --name tailwind.sql

az ssh 명령을 사용하여 Azure 가상 머신에 연결

az ssh vm \
    --resource-group 240900-linux-postgres \
    --name vm-1

스토리지 계정에서 tailwind.sql 파일 다운로드

Bash 변수 STORAGE_ACCOUNT_NAME을 스토리지 계정 이름으로 설정합니다.

STORAGE_ACCOUNT_NAME=$(az storage account list \
    --resource-group 240900-linux-postgres \
    --query '[0].name' \
    -o tsv)

echo "STORAGE_ACCOUNT_NAME: $STORAGE_ACCOUNT_NAME"

tailwind.sql 명령을 사용하여 az storage blob download을 Azure 가상 머신에 다운로드합니다.

az storage blob download \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --container-name container1 \
    --file tailwind.sql \
    --name tailwind.sql

원격 컴퓨터에서 psql에 대한 환경 변수 설정

MANAGED_IDENTITY_NAME=240900-linux-postgres-identity
export AZURE_CLIENT_ID=$(az identity show --resource-group 240900-linux-postgres --name $MANAGED_IDENTITY_NAME --query "clientId" -o tsv)
PG_NAME=$(az postgres flexible-server list --resource-group 240900-linux-postgres --query "[0].name" -o tsv)

# Set psql environment variables
export PGHOST="${PG_NAME}.privatelink.postgres.database.azure.com"
export PGPASSWORD=$(curl -s "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fossrdbms-aad.database.windows.net&client_id=${AZURE_CLIENT_ID}" -H Metadata:true | jq -r .access_token)
export PGUSER=$MANAGED_IDENTITY_NAME
export PGDATABASE=postgres

psql을 사용하여 tailwind.sql 가져오기

psql -f tailwind.sql

postgres 서버에 연결하여 가져오기가 성공했는지 확인

psql

테이블 나열

\dt

다음과 같은 출력이 표시됩니다.

postgres=> \dt
                           List of relations
 Schema |         Name         | Type  |             Owner              
--------+----------------------+-------+--------------------------------
 public | cart_items           | table | 240900-linux-postgres-identity
 public | checkouts            | table | 240900-linux-postgres-identity
 public | collections          | table | 240900-linux-postgres-identity
 public | collections_products | table | 240900-linux-postgres-identity
 public | customers            | table | 240900-linux-postgres-identity
 public | delivery_methods     | table | 240900-linux-postgres-identity
 public | product_types        | table | 240900-linux-postgres-identity
 public | products             | table | 240900-linux-postgres-identity
 public | shipment_items       | table | 240900-linux-postgres-identity
 public | shipments            | table | 240900-linux-postgres-identity
 public | store_inventory      | table | 240900-linux-postgres-identity
 public | stores               | table | 240900-linux-postgres-identity
 public | suppliers            | table | 240900-linux-postgres-identity
 public | supply_orders        | table | 240900-linux-postgres-identity
(14 rows)

테이블을 나열하는 SQL 쿼리 실행

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';

다음과 같은 출력이 표시됩니다.

postgres=> SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';
      table_name      
----------------------
 collections
 stores
 customers
 cart_items
 product_types
 products
 suppliers
 collections_products
 checkouts
 shipments
 delivery_methods
 shipment_items
 store_inventory
 supply_orders
(14 rows)

확장 모드를 켜고 제품 테이블에서 선택

postgres=> 프롬프트에서 확장 모드를 켭니다.

\x

제품 테이블에서 선택합니다.

select * from products;

다음과 같은 메시지가 나타납니다.

postgres=> \x
Expanded display is on.
postgres=> select * from products;

제품 목록이 나타납니다.

id                 | 1
product_type_id    | 1
supplier_id        | 2
sku                | brush_cleaner
name               | Meltdown Brush Cleaner
price              | 12.99
description        | We all leave our brushes sitting around, full of old dry paint. Don't worry! The Meltdown Brush Cleaner can remove just about anything.
image              | brush_cleaner.jpg
digital            | f
unit_description   | 1 - 10oz Jar
package_dimensions | 4x8x2
weight_in_pounds   | 3.2
reorder_amount     | 10
status             | in-stock
requires_shipping  | t
warehouse_location | Zone 1, Shelf 12, Slot 6
created_at         | ...
updated_at         | ...
...

스페이스바를 눌러 결과 페이지를 넘겨 봅니다. q를 입력하여 페이지 선택기를 종료합니다.

psql 종료

\q

명령줄을 통해 애플리케이션을 대화형으로 실행

원격 컴퓨터에서 애플리케이션이 포함된 디렉터리로 변경합니다.

cd tailwind-traders-go/app

명령줄에서 대화형으로 애플리케이션 실행:

go run main.go app:serve

다음과 같은 출력이 표시됩니다.

$ go run main.go app:serve
Listening on :8080

VM의 공용 IP 주소 찾기

가상 머신의 공용 IP 주소 확인:

IP_ADDRESS=$(az network public-ip show \
    --resource-group 240900-linux-postgres \
    --name vm-1-ip \
    --query ipAddress \
    --out tsv)

터미널에 URL 출력:

echo "Your URL is: http://${IP_ADDRESS}:8080"

이 장치는 대화형 개발/테스트 목적으로 포트 8080을 사용합니다. 프로덕션에서는 포트 443을 사용하고 엔드포인트에 대한 트래픽을 보호하도록 하려면 TLS 인증서가 필요합니다.

공용 API 엔드포인트 찾아보기

웹 브라우저에서 URL을 엽니다. 다음과 같은 출력이 표시됩니다.

{
  "id": 5,
  "product_type_id": 1,
  "supplier_id": 2,
  "sku": "drafting_tools",
  "name": "Bespoke Drafting Set",
  "price": 45,
  "description": "Build your next bridge (or tunnel) using our Bespoke Drafting Set. Everyone drives across *regular* bridges everyday - but they'll rememeber yours - because it's _bespoke_.",
  "image": "drafting_tools.jpg",
  "digital": false,
  "unit_description": "Tools and carrying case",
  "package_dimensions": "5x10x3",
  "weight_in_pounds": "1.2",
  "reorder_amount": 10,
  "status": "in-stock",
  "requires_shipping": true,
  "warehouse_location": "Zone 1, Shelf 4, Slot 1",
  "created_at": "...",
  "updated_at": "..."
}

또는 curl을 사용하여 API 엔드포인트에 요청을 할 수 있습니다.

curl "http://${IP_ADDRESS}:8080"

이 엔드포인트는 데이터베이스에서 임의의 제품을 표시합니다.

터미널에 기록된 요청 보기

애플리케이션을 대화형으로 실행하는 터미널로 돌아갑니다. 출력에는 API 엔드포인트에 대한 요청이 표시됩니다.

{"time":"...","level":"INFO","msg":"httpLog","remoteAddr":"[::1]:58592","method":"GET","url":"/"}
{"time":"...","level":"INFO","msg":"httpLog","remoteAddr":"[::1]:59414","method":"GET","url":"/"}
{"time":"...","level":"INFO","msg":"httpLog","remoteAddr":"[::1]:59414","method":"GET","url":"/favicon.ico"}

이러한 요청이 성공하면 애플리케이션 워크로드가 Azure 가상 머신과 Azure Database for PostgreSQL(유연한 서버)로 마이그레이션됩니다.

Azure 리소스 정리

Linux 및 PostgreSQL 워크로드 탐색을 마치면 리소스를 정리하여 비용을 절감합니다.

Azure Portal을 통해 리소스 그룹 240900-linux-postgres를 수동으로 삭제하거나 다음 Azure CLI 명령을 실행할 수 있습니다.

az group delete \
    --name 240900-linux-postgres \
    --yes \
    --no-wait

또 다른 옵션은 empty.bicep 템플릿을 사용하여 vm-postgres.bicep 파일이 만든 리소스를 삭제하는 것입니다. az deployment group create와 함께 --mode Complete를 실행하면 템플릿에서 정의하지 않은 모든 리소스가 제거됩니다. empty.json에 리소스가 없으므로 명령은 모든 리소스를 삭제합니다.

az deployment group create \
    --resource-group 240900-linux-postgres \
    --template-file deploy/empty.bicep \
    --mode Complete

empty.json을 배포하면 240900-linux-postgres 리소스 그룹은 그대로 유지되므로 단일 명령을 사용하여 리소스를 다시 배포할 수 있습니다.

리소스