k8s nginx代替ingress

架构

k8s nginx代替ingress_第1张图片
四层代理部分,可以采用nginx、haproxy、ipvsadm等。

机器

192.168.112.4
系统:centos7.9.2009
准备:k8s单机,nginx

pod容器:web服务

pod部分:名为test-hello的nginx web服务

# cat test-hello.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-hello
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: test-hello
  template:
    metadata:
      labels:
        app: test-hello
    spec:
      containers:
      - name: test-hello
        image: nginx:1.17
        imagePullPolicy: IfNotPresent
        resources:
          requests:
            cpu: 100m
            memory: 500Mi
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: test-hello
spec:
  selector:
    app: test-hello
  ports:
  - name: http
    port: 80
    targetPort: 80

将3个pod实例的/usr/share/nginx/html/index.html分别改为1、2、3

kubectl exec -it test-hello-xxx -- bash
echo 1 > /usr/share/nginx/html/index.html
echo 2 > /usr/share/nginx/html/index.html
echo 3 > /usr/share/nginx/html/index.html

容器:nginx7层代理

nginx-test,七层代理,起到替代ingress的作用,采用NodePort方式暴露该nginx到30080端口

# cat nginx-test.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-test
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx-test
  template:
    metadata:
      labels:
        app: nginx-test
    spec:
      containers:
      - name: nginx-test
        image: nginx:1.17
        imagePullPolicy: IfNotPresent
        resources:
          requests:
            cpu: 100m
            memory: 500Mi
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-test
spec:
  selector:
    app: nginx-test
  type: NodePort
  ports:
  - name: http
    port: 80
    targetPort: 80
    nodePort: 30080
配置

proxy_pass到test-hello的service

# cat default.conf 
server {
    listen       80;
    server_name  www.abc.com;
    location / {
        proxy_pass http://test-hello;
    }
}

机器本地:nginx4层代理

yum install nginx -y
# 其中--with-stream模块起到4层代理功能

下面这部分4层代理的配置加到nginx.conf文末,与http同级

stream {
    # 添加socket转发的代理
    upstream socket_proxy {
        hash $remote_addr consistent;
        # 转发的目的地址和端口
        server 192.168.112.4:30080 weight=5 max_fails=3 fail_timeout=30s;
    }
 
    # 提供转发的服务,即访问localhost:30080 ,会跳转至代理socket_proxy指定的转发地址
    server {
       listen 80;
       proxy_connect_timeout 1s;
       proxy_timeout 3s;
       proxy_pass socket_proxy;
    }
} 

测试

绑hosts
echo "192.168.112.4 www.abc.com" >> /etc/hosts

k8s nginx代替ingress_第2张图片
k8s nginx代替ingress_第3张图片

你可能感兴趣的:(docker,&,k8s,kubernetes,nginx,docker,容器)