使用nginx 正向代理暴露k8s service && pod ip 外部直接訪問


有時在我們的實際開發中我們希望直接訪問k8s service 暴露的服務,以及pod的ip
解決方法,實際上很多

  • nodeport
  • ingress
  • port-forword
    實際上我們還有一種方法:正向代理

nginx 正向代理配置

為了簡單,只處理http 流量,實際上我們可以基於envoy 搞這個事情也是很不錯的

  • nginx conf
 
worker_processes 1;
events {
    worker_connections 1024;
}
http {
    include mime.types;
    resolver 10.254.8.8; # 比較重要
    default_type application/octet-stream;
    server {
        listen 8080;
        charset utf-8;
        location / {
   proxy_pass http://$http_host$request_uri;
        }
    }
}
  • dockerfile
FROM nginx
COPY nginx.conf /etc/nginx/nginx.conf
  • k8s 部署
    service nodeport 類型
 
apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: kompose -f docker-compose.yaml convert -o k8s
    kompose.version: 1.17.0 ()
  creationTimestamp: null
  labels:
    io.kompose.service: proxy
  name: proxy
spec:
  type: NodePort
  ports:
  - name: "8080"
    port: 8080
    targetPort: 8080
  selector:
    io.kompose.service: proxy
status:
  loadBalancer: {}
 

Deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose -f docker-compose.yaml convert -o k8s
    kompose.version: 1.17.0 ()
  creationTimestamp: null
  labels:
    io.kompose.service: proxy
  name: proxy
spec:
  replicas: 1
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        io.kompose.service: proxy
    spec:
      containers:
      - image: dockerimagehost/library/nginx-proxy
        name: proxy
        ports:
        - containerPort: 8080
      restartPolicy: Always
status: {}
 
 

配置proxy

這個我們可以根據自己的系統配置,mac,linux ,Windows,都少有不同

  • 使用curl 測試
curl --proxy http://nodeid:nodeport http://10.254.198.240:8500
  • 配置了全局proxy 的訪問

    此ip 為service ip 實際上直接使用pod ip 也是可以訪問的

 

說明

以上是一個簡單的實踐,實際上上一些service mesh 的框架實現也是這種模式進行不通流量的處理的

參考資料

http://nginx.org/en/docs/http/ngx_http_proxy_module.html 
https://github.com/rongfengliang/nginx-forward-for-k8s-pod-ip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM