Romer Alvarez
← Todos los artículos

Despliegue de aplicaciones básicas en Azure Kuberentes Service (AKS)

Despliegue de Aplicaciones en Azure Kubernetes Service (AKS): Introducción básica.

Introducción

En este artículo exploraremos cómo desplegar aplicaciones utilizando Azure Kubernetes Service (AKS). Cubriremos desde la creación de un Azure Container Registry hasta el despliegue de imágenes de contenedores en AKS, ilustrado con ejemplos prácticos y diagramas explicativos.

Relation between ACR and AKS

Estaremos realizando el ejercicio propuesto por Microsoft.

Se compone de 4 ejercicios:

Ejercicio 1: Aprovisionamiento de Azure Container Registry (ACR) y Azure Kubernetes Service (AKS)

Paso 1: Crear un Azure Container Registry (ACR)

  1. Iniciar sesión en el portal de Azure.
  2. Buscar en la barra de búsqueda Container Registries. Haz clic en + Create y completa los siguientes datos:
Configuración Valor
Subscription Tu suscripción de Azure
Resource Group acr-01-RG
Registry name Debe ser un nombre único, en nuestro será romeralvarezme
Region Europe West
Availability zones Ninguno
SKU Basic

Paso 2: Crear una Azure Virtual Network and an AKS Cluster

Creación de una red virtual y un clúster de AKS.

  1. Buscar en la barra de búsqueda Virtual Network. Haz clic en + Create y completa los siguientes datos:
Configuración Valor
Subscription Tu suscripción de Azure
Resource Group aks-01-RG
Virtual network name vnet-01
Region [La misma región que antes]
  1. Buscar en la barra de búsqueda Kubernetes Service. Haz clic en + Create y completa los siguientes datos:
Configuración Valor
Subscription Tu suscripción de Azure
Resource Group aks-01-RG
Cluster preset configuration Dev/Test
Kubernetes cluster name aks-01
Region [La misma región que antes]
Availability zones Ninguno
AKS pricing tier Free
Kubernetes version [Valor por defecto]
Automatic upgrade Disabled
Node size Standard B4ms
Scale method Manual
Node count 2
Configuración Valor
Cluster subnet aks-subnet (10.0.0.0/20)
Kubernetes service address range 172.16.0.0/22
Kubernetes DNS service IP address 172.16.3.254
DNS name prefix aks-01-dns
Enable private cluster Disabled
Set authorized IP ranges Disabled
Network policy None
  1. Crearemos el Pool de Nodos Windows:
Configuración Valor
Node pool name w1pool
Mode User
OS type Windows
Availability zone Ninguno
Enable Azure spot instances Disabled
Node size Standard B4s_v2
Scale method Manual
Node count 2
Max pods per node 30
Enable public IP per node Disabled
  1. En la pestaña de Integrations seleccionaremos el Registry que hemos creado anteriormente, nos aseguraremos de desactivar Azure Monitor y Azure Policy y seleccionaremos Review + Create y luego Create.

Ahora, esperaremos a que se aprovisionen los recursos, y podemos dar por concluido el ejercicio 1. Habremos completado lo siguiente:

Y se nos quedaría algo de este estilo: ACR and AKS

Ejercicio 2: Crear imágenes de contenedores Linux y Windows y almacenarlas en Azure Container Registry

En este ejercicio, crearemos imágenes de contenedores Linux y Windows y las almacenaremos en Azure Container Registry (ACR).

Paso 1: Configuración del entorno

mkdir ~/image-l01
cd ~/image-l01
vim server.js

Paso 2: Creación de archivos para el proyecto de Linux

const http = require('http')
const port = 80
const server = http.createServer((request, response) => {
  response.writeHead(200, {'Content-Type': 'text/plain'})
  response.write('Hello World from Node\n')
  response.end('Version: ' + process.env.NODE_VERSION + '\n')
})
server.listen(port)
console.log(`Server running at http://localhost: ${port}`)
{
  "name": "helloworld",
  "version": "1.0.0",
  "description": "Sample app for ACR Build",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "license": "MIT"
}
FROM node:20.2-alpine
COPY . /src
RUN cd /src && npm install
EXPOSE 80
CMD ["node", "/src/server.js"]
ACR_RG='acr-01-RG'
ACR_NAME=$(az acr list --resource-group $ACR_RGNAME --query "[].name" --output tsv)
az acr build --registry $ACR_NAME --image hellofromnode:v1.0 .

### Paso 3: Creación de archivos para el proyecto de Windows

mkdir ~/image-w01
cd ~/image-w01
git clone https://github.com/Azure-Samples/dotnetcore-docs-hello-world.git
cd ~/image-w01/dotnetcore-docs-hello-world
az acr build --registry $ACR_NAME --image hellofromdotnet:v1.0 --platform windows --file Dockerfile.windows .

Al ir a nuestro Registry, veremos que tenemos las dos imágenes creadas:

ACR Repository

Ejercicio 3: Desplegar contenedores en Azure Kubernetes Service

En esta tarea crearemos dos namespaces en nuestro cluster de AKS y desplegaremos las imágenes que hemos creado en el ejercicio anterior.

Paso 1: Crear namespaces

  1. En el portal de Azure, buscaremos Kubernetes Services y seleccionaremos nuestro cluster de AKS.
  2. En la pestaña de Kubernetes Resources seleccionaremos Namespaces y crearemos uno llamado dev-node y otro llamado dev-dotnet.

Paso 2: Creare manifiestos para desplegar la imagen de y Windows

  1. En nuestro Cloud Shell, crearemos el siguiente directorio:
mkdir ~/aks-l01
cd ~/aks-l01
  1. Crearemos el siguiente archivo de manifiesto de Kubernetes aks-deployment-l01.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hellofromnode-deployment
  labels:
    environment: dev
    app: hellofromnode
spec:
  replicas: 1
  template:
    metadata:
      name: hellofromnode
      labels:
        app: hellofromnode
    spec:
      nodeSelector:
        "kubernetes.io/os": linux
      containers:
      - name: hellofromnode
        image: ACR_NAME.azurecr.io/hellofromnode:v1.0
        resources:
          limits:
            cpu: 1
            memory: 800M
        ports:
          - containerPort: 80
  selector:
    matchLabels:
      app: hellofromnode
---
apiVersion: v1
kind: Service
metadata:
  name: hellofromnode-service
spec:
  type: LoadBalancer
  ports:
  - protocol: TCP
    port: 80
  selector:
    app: hellofromnode
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hellofromdotnet-deployment
  labels:
    environment: dev
    app: hellofromdotnet
spec:
  replicas: 1
  template:
    metadata:
      name: hellofromdotnet
      labels:
        app: hellofromdotnet
    spec:
      nodeSelector:
        "kubernetes.io/os": windows
      containers:
      - name: hellofromdotnet
        image: ACR_NAME.azurecr.io/hellofromdotnet:v1.0
        resources:
          limits:
            cpu: 1
            memory: 800M
        ports:
          - containerPort: 80
  selector:
    matchLabels:
      app: hellofromdotnet
---
apiVersion: v1
kind: Service
metadata:
  name: hellofromdotnet-service
spec:
  type: LoadBalancer
  ports:
  - protocol: TCP
    port: 80
  selector:
    app: hellofromdotnet
  1. Reemplazaremos ACR_NAME con el nombre de nuestro Azure Container Registry (ACR) y ejecutaremos el siguiente comando para desplegar la imagen de Linux:
sed -i "s/ACR_NAME/$ACR_NAME/" ./aks-deployment-w01.yaml
kubectl apply -f ./aks-deployment-w01.yaml -n dev-node

Paso 3: Desplegar los manifiestos en sus respectivos namespaces:

  1. En nuestra sesión de bash, nos conectaremos al cluster con los siguientes comandos:
AKSRG='aks-01-RG'
AKSNAME='aks-01'
az aks get-credentials --resource-group $AKSRG --name $AKSNAME
  1. Verificar que la conexión se ha realizado correctamente:
kubectl get nodes
  1. Desplegaremos los manifiestos en sus respectivos namespaces:
kubectl apply -f aks-l01/aks-deployment-l01.yaml -n dev-node
kubectl apply -f aks-w01/aks-deployment-w01.yaml -n dev-dotnet
  1. Verificaremos que los pods se han creado correctamente:
kubectl get pods -n dev-node
kubectl get pods -n dev-dotnet
  1. Verificaremos que los servicios se han creado correctamente:
kubectl get services -n dev-node
kubectl get services -n dev-dotnet

Y finalmente, podremos ver que tenemos los pods y los servicios creados correctamente:

romer [ ~ ]$ kubectl get pods -n dev-node
NAME                                READY   STATUS    RESTARTS   AGE
hellofromnode-deployment-65bb76d95f-8wp4c   1/1     Running   0          4m41s

romer [ ~ ]$ kubectl get pods -n dev-dotnet
NAME                                 READY   STATUS    RESTARTS   AGE
hellofromdotnet-deployment-66445d8f4-jwtv7   1/1     Running   0          4m39s

romer [ ~ ]$ kubectl get services -n dev-dotnet
NAME                           TYPE           CLUSTER-IP      EXTERNAL-IP       PORT(S)          AGE
hellofromdotnet-service        LoadBalancer   172.16.0.112    4.175.193.225     80:30614/TCP     4m44s

romer [ ~ ]$ kubectl get services -n dev-node
NAME                         TYPE           CLUSTER-IP      EXTERNAL-IP       PORT(S)          AGE
hellofromnode-service        LoadBalancer   172.16.3.220    4.175.193.210     80:32568/TCP     4m53s

Ejercicio 4: Eliminar todos los recursos

Es sumamente importante eliminar todos los recursos que hemos creado para no incurrir en costes innecesarios. Lo podremos hacer de la siguiente manera, en la misma sesión de bash:

az group delete --resource-group $ACR_RG --yes --no-wait
az group delete --resource-group $AKSRG --yes --no-wait