用负载均衡来保护外部的NATS访问

Using a Load Balancer for External Access to NATS

In the example below, you can find how to use an AWS Network Load Balancer to connect externally to a cluster that has TLS setup.

One-line installer creates a secure cluster named 'nats'

curl -sSL https://nats-io.github.io/k8s/setup.sh | sh

Create AWS Network Load Balancer service

echo '
apiVersion: v1
kind: Service
metadata:
  name: nats-nlb
  namespace: default
  labels:
    app: nats
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ports:
  - name: nats
    port: 4222
    protocol: TCP
    targetPort: 4222
  selector:
    app.kubernetes.io/name: nats
' | kubectl apply -f -

Check that it worked

Publish a test message

Also, it would be recommended to set no_advertise to true in order to avoid gossiping internal addresses from pods in Kubernetes to NATS clients.

Setting up a NATS Server with external access on Azure

With the following, you can create a 3-node NATS Server cluster:

The configuration map from the NATS cluster that was created can be found below.

Now let's expose the NATS Server by creating an L4 load balancer on Azure:

Confirm the public IP that was allocated to the nats-lb service that was created, in this case it is 52.155.49.45:

Notice that the leafnode configuration requires authorization, so in order to connect to it we will need to configuration as follows:

You can also add a NATS Streaming cluster into the cluster connecting to the port 4222:

Now if you create two NATS Servers that connect to the same leafnode port, they will be able to receive messages to each other:

Create a subscriber and publish a test message

最后更新于