Azure App Service 使用 Web Job 進行自動重新啟動
一、前言
Web應用程式有時會需要進行重新啟動,例如修改設定檔後,需重新啟動才能使新設定生效,一般情況下,我們可以手動重啟,但有時會透過排程來修改設定檔,排程時間一般會在深夜或凌晨這種較少人使用的休息時間執行,所以人工重啟是不切實際的行為,較好的方法是在排程執行完成,進行自動重啟。
因應雲端服務的興起,以往的Web應用程式,在成本、維護、安全等各種考量下,逐漸改在雲端服務平台上建置,前述的自動重啟需求,在雲端上也會有。近期的專案使用Microsoft Azure的App Service建置網站,就有排程工作後要自動重啟的需求,接下來會說明如何使用Web Job功能使App Service自動重啟。
二、建置程序
關於App Service的建置,在此不會進行說明,本文章的重點在如何進行自動重啟的操作,以下說明操作步驟。
1. Web Job(Web工作)是App Service的功能之一,能執行可執行檔或指令碼,用來執行一些背景工作,支援下列檔案類型:
- .cmd、.bat、.exe (使用 Windows 命令提示字元)
- .ps1 (使用 PowerShell)
- .sh (使用 Bash)
- .php (使用 PHP)
- .py (使用 Python)
- .js (使用 Node.js)
- .jar (使用 Java)
2. 我們重新啟動的方式,是透過PowerShell執行指令碼來達成,指令碼如下所示:
$resourceGroupName = "your-azure-web-app-resource-group-name"
$webappName = "your-azure-web-app-name"
$username = "your-azure-login-name"
$password = ConvertTo-SecureString "your-azure-login-password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Write-Output "Login to azure environment"
Login-AzureRmAccount -Credential $cred
Write-Output "Restarting Web App..."
Restart-AzureRmWebApp -Name $webappName -ResourceGroupName $resourceGroupName
Write-Output "Operation Completed."
3. 將指令中的變數,替換為實際的Azure服務名稱及登入帳號、密碼,如下表所示:
變數名 |
說明 |
範例值 |
$resourceGroupName |
資源群組名稱 |
your-azure-web-app-resource-group-name |
$webappName |
App Service名稱 |
your-azure-web-app-name |
$username |
Azure登入帳號 |
your-azure-login-name |
$password |
Azure登入密碼 |
your-azure-login-password |
4. 將指令碼存成run.ps1。
5. 進入已建置的 App Service ,點選左側選單的設定->Web工作,開啟Web工作設定,如下圖所示:
6. 點選[+新增],開啟加入Web工作視窗,輸入表單內容如下所示:
名稱:自訂名稱
檔案上傳:前述建立的重啟檔案
類型:觸發式
觸發程序:手動
7. 選擇建立的Web Job,點選屬性,開啟屬性資料。
8. 在屬性資料視窗,複製WEBHOOK、使用者名稱、密碼。
9. 我們在執行排程工作後,在程式中透過呼叫WEBHOOK,來觸發Web Job以達到自動重啟的目的,下列是呼叫WEBHOOK程式範例:
private async Task Restart(string webhook,string user, string password)
{
var httpClient = new HttpClient();
var authenticationString = $"{user}:{password}";
var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.ASCII.GetBytes(authenticationString));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
var response = await httpClient.PostAsync(webhook, null);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Restart success");
}
else
{
Console.WriteLine("Restart failed");
}
}
三、參考資料