有时在我们的实际开发中我们希望直接访问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