Create a Deployment for the Web Application
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app-deployment
spec:
replicas: 3
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: web-app-container
image: your-web-app-image:tag
ports:
- containerPort: 8080
Create a Service to Expose the Web Application
apiVersion: v1
kind: Service
metadata:
name: web-app-service
spec:
selector:
app: web-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer
Apply the Deployments and Service
kubectl apply -f web-app-deployment.yaml
kubectl apply -f web-app-service.yaml
Access the Exposed Web Application
kubectl get service web-app-service
Look for the "EXTERNAL-IP" field, which will provide the external IP address assigned to the Service. Open a web browser and enter the external IP address to access the web application.
Discovering Services and Pods using DNS
Discovering a Service using DNS
import socket
service_host = "my-service.default.svc.cluster.local"
service_port = 80
service_address = socket.gethostbyname(service_host)
print(f"Service IP: {service_address}")
Discovering a Pod using DNS
import socket
pod_host = "my-pod.default.pod.cluster.local"
pod_port = 8080
pod_address = socket.gethostbyname(pod_host)
print(f"Pod IP: {pod_address}")
Kubernetes API
from kubernetes import client, config
config.load_kube_config()
api_instance = client.CoreV1Api()
services = api_instance.list_service_for_all_namespaces().items
for service in services:
print(f"Service Name: {service.metadata.name}")
print(f"Service Namespace: {service.metadata.namespace}")
print(f"Service IP: {service.spec.cluster_ip}")
print("---")
Ingress
from kubernetes import client, config
config.load_kube_config()
api_instance = client.ExtensionsV1beta1Api()
ingresses = api_instance.list_ingress_for_all_namespaces().items
for ingress in ingresses:
print(f"Ingress Name: {ingress.metadata.name}")
print(f"Ingress Namespace: {ingress.metadata.namespace}")
for rule in ingress.spec.rules:
print(f"Host: {rule.host}")
for path in rule.http.paths:
print(f"Path: {path.path}")
print(f"Service: {path.backend.service_name}")
print(f"Service Port: {path.backend.service_port}")
print("---")