DEV Community

Tossapol Ritcharoenwattu
Tossapol Ritcharoenwattu

Posted on

Kubernetes Workshop1 : Step10 : Service Loadbalancer

เราจะมาลองทำ service loadbalancer ด้วย minikube กัน
เราจะสร้าง pod nginx ขึ้นมาก่อน

ถ้าเรายังไม่ได้สร้าง loadbalancer เราจะไม่สามารถ curl ไปยัง nginx จากภายนอก container ได้

ip : 192.168.49.2 เป็น ip ของ minikube node ยังไม่มีการสร้าง service จึงไม่สามารถ curl ได้
ip : 10.244.0.108 เป็น ip ของ pod ที่อยู่ภายใน node ไม่สามาถเรียก curl จากภายนอกได้
ถ้าอยากเรียก curl http://10.244.0.108 ต้อง ssh เข้าไปใน node ก่อน

สร้าง service loadbalancer เพื่อให้สามารถเข้าถึง nginx จากภายนอกได้
1. สร้างไฟล์ service-definition.yaml

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30008
  selector:
    app: nginx
    tier: frontend
Enter fullscreen mode Exit fullscreen mode

ในส่วนของ selector ต้องกำหนดให้ตรงกับ label ของ pod ที่สร้างไว้ และสั่ง apply

kubectl apply -f service-definition.yaml
Enter fullscreen mode Exit fullscreen mode


จะพบว่ามี service ประเภท loadbalancer ถูกสร้างขึ้นมา

2. เปิด minikube tunnel จำลอง load balance ในเครื่อง
ให้เปิด terminal ใหม่ขึ้นมา run คำสั่ง และห้ามปิด

minikube tunnel
Enter fullscreen mode Exit fullscreen mode

_3. ทดสอบการทำงาน _
สำหรับการใช้ minikube tunnel นี้ เป็นการจำลอง loadbalance จึงไม่สามารถเรียก curl ไปยัง port 30008 ที่กำหนดได้ จะต้อง run command เพื่อดู port ที่สามารถเรียกจาก tunnel ได้ก่อน

minikube service myapp-service
Enter fullscreen mode Exit fullscreen mode


จะเปิดหน้า web ขึ้นมาตาม url http://127.0.0.1:64208

Top comments (0)