Deploying a Web Application on Azure Kubernetes Service (AKS): A Step-by-Step Guide for Beginners!

Deploying a Web Application on Azure Kubernetes Service (AKS): A Step-by-Step Guide for Beginners!

Hi Friends,

In this article, I'll guide you through a small project to run a web application using Docker, containers, and Azure Kubernetes Service (AKS).

This guide is specifically designed for audiences who are new to Docker, Kubernetes, and application deployment concepts.

We'll cover everything step-by-step, ensuring you can follow along even if you're a beginner.

Use case:

Deploy a basic web application using Docker containers on AKS. This example will have minimal cost as it uses the Azure free tier and simple resources.

Steps to Implement:

The entire process requires 4 main steps-

  1. Create a docker container for your web application
  2. Create an Azure Container Registry (ACR)
  3. Create an Azure Kubernetes Service (AKS)
  4. Deploy the web application on AKS
  5. Access your web application


Create a docker container for web application -

  1. Create a web application: I am going to use the same application I created using flask. Refer my article My First Web Application with Flask: A Beginner's Guide! | LinkedIn
  2. Create a Dockerfile to define the container:

# Use the official Python image from Docker Hub
FROM python:3.12-slim # Specifies the base image to use

# Install Flask library
RUN pip install flask

# Copy the app.py file into the container
COPY Myfirstflaskproject.py /Myfirstflaskproject.py

# Define the command to run the web application when the container starts
CMD ["python", "Myfirstflaskproject.py"]        

3. Build the docker image: The docker build command creates a Docker image that encapsulates your application and all its dependencies, ensuring it can run consistently across different environments.

docker build -t myfirstflaskproject-app-image .        

This command builds a Docker image from the Dockerfile in the current directory (.) and tags it as myfirstflaskproject-app-image. Tip to run and check the docker container use below command-

docker run -p 5000:5000 myfirstflaskproject-app-image        



Docker Desktop

Create an Azure Container Registry (ACR)

1. Go to the Azure Portal

Sign in to your Azure account at https://portal.azure.com.

2. Create a Container Registry

  1. In the Azure Portal, click on "Create a resource" and search for "Container Registry".
  2. Follow the prompts to create a new Container Registry. Choose the Basic tier for minimal cost.


Azure Container Registry

3. Push Your Docker Image to ACR

Back in your terminal, log in to your ACR and push your Docker image:

az acr login --name acrdemotechysvault
docker tag myfirstflaskproject-app-image acrdemotechysvault.azurecr.io/myfirstflaskproject-app-image:v1
docker push acrdemotechysvault.azurecr.io/myfirstflaskproject-app-image:v1        
VS Code - Push docker Image to Registry

Explanation:

az acr login --name acrdemotechysvault: Logs in to your Azure Container Registry.

docker tag myfirstflaskproject-app-image acrdemotechysvault.azurecr.io/myfirstflaskproject-app-image:v1: Tags your local Docker image with the registry name.

docker push acrdemotechysvault.azurecr.io/myfirstflaskproject-app-image:v1: Pushes the tagged image to your Azure Container Registry.


Create an Azure Kubernetes Service (AKS) Cluster

1. Create an AKS Cluster

  1. In the Azure Portal, click on "Create a resource" and search for "Kubernetes Service".
  2. Follow the prompts to create a new AKS cluster. Choose the default settings to minimize costs.


Azure Kubernetes Service

2. Configure kubectl

Back in your terminal, get the credentials to connect to your AKS cluster:

#Retrieves the credentials to manage your AKS cluster using kubectl.
az aks get-credentials --resource-group Demo-RG --name aks-demo-techysvault        

Deploy the Web Application on AKS

1. Create a Deployment and Service YAML File

Create a new file in VS Code named my-web-app-deployment.yaml.

In my-web-app-deployment.yaml, add the following code:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: flask-app
  template:
    metadata:
      labels:
        app: flask-app
    spec:
      containers:
      - name: flask-app
        image: acrdemotechysvault.azurecr.io/myfirstflaskproject-app-image:v1
        ports:
        - containerPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: my-web-app-service
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 5000
  selector:
    app: flask-app        

Explanation: This YAML file defines two Kubernetes resources: a Deployment and a Service.

Deployment:

  • apiVersion: apps/v1: Specifies the API version.
  • kind: Deployment: Indicates that this is a Deployment resource.
  • metadata: Contains metadata about the deployment, such as the name.
  • spec: Specifies the desired state of the deployment, including the number of replicas, selectors, and template.
  • template: Describes the pod template, including labels and containers.
  • containers: Lists the containers in the pod, including the image and ports.

Service:

  • apiVersion: v1: Specifies the API version.
  • kind: Service: Indicates that this is a Service resource.
  • metadata: Contains metadata about the service, such as the name.
  • spec: Specifies the desired state of the service, including type, ports, and selector.

2. Apply the YAML File

In your terminal, run the following command to apply the YAML file and deploy your application:

kubectl apply -f my-web-app-deployment.yaml        

Applies the configuration in the YAML file, creating the Deployment and Service in your AKS cluster.


Access Your Web Application

1. Get the External IP

Run the following command to get the external IP of your service:

kubectl get services my-web-app-service        
External IP - 52.140.91.177



Issues Encountered:

  • Error#: The below error message you're seeing indicates that there's an issue with authentication when trying to pull the image from your Azure Container Registry (ACR). This usually happens when the Kubernetes cluster doesn't have the correct permissions to access the ACR.

Once you have implemented the below solution, try pulling the image again using kubectl apply -f my-web-app-deployment.yaml

Error#1
Failed to pull image "acrdockerwebapp.azurecr.io/my-web-app:v1": failed to pull and unpack image "acrdockerwebapp.azurecr.io/my-web-app:v1": failed to resolve reference "acrdockerwebapp.azurecr.io/my-web-app:v1": failed to authorize: failed to fetch anonymous token: unexpected status from GET request to https://acrdockerwebapp.azurecr.io/oauth2/token?scope=repository%3Amy-web-app%3Apull&service=acrdockerwebapp.azurecr.io: 401 Unauthorized

Solution#1
Get the service principal ID or Managed Identity ID and assign role ACRpull

#To check the ID
az aks show --resource-group <your-resource-group> --name <your-aks-cluster> --query "servicePrincipalProfile.clientId" -o tsv
az aks show --resource-group <your-resource-group> --name <your-aks-cluster> --query "identityProfile.kubeletidentity.objectId" -o tsv

#Assign ACRPull role
az role assignment create --assignee <managed-identity-object-id> --role AcrPull --scope /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.ContainerRegistry/registries/<acr-name>        

Additional commands for troubleshooting:

  • To check whether the pod is running healthy use below commands if you encounter any issues-

kubectl get pods -l app=my-web-app
kubectl describe pod <pod-name>        

To check the pod logs

kubectl logs <pod-name>        

To check DNS resolution is working correctly within the cluster use below command

kubectl exec -it <pod-name> -- nslookup my-web-app-service        

To avoid error - "az : The term 'az' is not recognized as the name of a cmdlet, function, script file, or operable program." This error you will encounter if you are new to programming and trying to run az command in your local terminal. Solution is to set environment variable as given below and restart VS Code IDE

#Get the path of az command
Get-Command az

#Edit in settings.json in VS code
{
    "terminal.integrated.env.windows": {
        "Path": "C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\CLI2\\wbin;${env:Path}"
    }
}        

If you encounter error related to docker -"The term 'docker' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." ,follow below steps

Install docker desktop. After installation add docker path to environment variables if necessary.

#Verify installation
docker --version        

Conclusion

By following these steps, you can successfully deploy a simple web application on Azure Kubernetes Service (AKS) using Docker containers.

It is important to note that while this guide provides an overview of the deployment process, it does not follow all best practices for production environments. The primary intention is to give you a foundational understanding of how to deploy a web application using Docker and AKS. This approach ensures minimal costs by leveraging the Azure free tier and simple resources.

With AKS, you have the tools to efficiently manage and scale your applications in the cloud, providing a robust platform for your development projects.

Enjoy learning and sharing ??

Thank You All ??


Temidayo Omoniyi

Platform Data Engineer ? Solutions Architect ? Software Engineer ? MCT ? Author

2 周

Thanks for sharing this. Most appreciated!

要查看或添加评论,请登录

Preetha R.的更多文章

其他会员也浏览了