Repository: pires/kubernetes-nats-cluster
Branch: master
Commit: 9cb5e43b8ad8
Files: 7
Total size: 22.2 KB
Directory structure:
gitextract_wobrug95/
├── .gitignore
├── LICENSE
├── README.md
├── nats.conf
├── nats.yml
├── route_checker/
│ └── main.go
└── ssl.cnf
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.pem
*.csr
*.srl
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# kubernetes-nats-cluster
NATS cluster on top of Kubernetes made easy.
**THIS PROJECT HAS BEEN ARCHIVED. SEE https://github.com/nats-io/nats-operator**
**NOTE:** This repository provides a configurable way to deploy secure, available
and scalable NATS clusters. However, [a _smarter_ solution](https://github.com/pires/nats-operator)
in on the way (see [#5](https://github.com/pires/kubernetes-nats-cluster/issues/5)).
## Pre-requisites
* Kubernetes cluster v1.8+ - tested with v1.9.0 on top of [Vagrant + CoreOS](https://github.com/pires/kubernetes-vagrant-coreos-cluster)
* At least 3 nodes available (see [Pod anti-affinity](#pod-anti-affinity))
* `kubectl` configured to access your cluster master API Server
* `openssl` for TLS certificate generation
## Deploy
We will be deploying a cluster of 3 NATS instances, with the following set-up:
- TLS on for clients, but not clustering because peer-auth requires real SANS DNS in certificate
- NATS client credentials: `nats_client_user:nats_client_pwd`
- NATS route/cluster credentials: `nats_route_user:nats_route_pwd`
- Logging: `debug:false`, `trace:true`, `logtime:true`
First, make sure to change `nats.conf` according to your needs.
Then create a Kubernetes configmap to store it:
```bash
kubectl create configmap nats-config --from-file nats.conf
```
Next, we need to generate valid TLS artifacts:
```bash
openssl genrsa -out ca-key.pem 2048
openssl req -x509 -new -nodes -key ca-key.pem -days 10000 -out ca.pem -subj "/CN=kube-ca"
openssl genrsa -out nats-key.pem 2048
openssl req -new -key nats-key.pem -out nats.csr -subj "/CN=kube-nats" -config ssl.cnf
openssl x509 -req -in nats.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out nats.pem -days 3650 -extensions v3_req -extfile ssl.cnf
```
Then, it's time to create a couple Kubernetes secrets to store the TLS artifacts:
- `tls-nats-server` for the NATS server TLS setup
- `tls-nats-client` for NATS client apps setup - one will need it to validate the self-signed certificate
used to secure NATS server
```bash
kubectl create secret generic tls-nats-server --from-file nats.pem --from-file nats-key.pem --from-file ca.pem
kubectl create secret generic tls-nats-client --from-file ca.pem
```
**ATTENTION:** Both using self-signed certificates and using the same certificates for securing
client and cluster connections is a significant security compromise. But for the sake of showing
how it can be done, I'm fine with doing just that.
In an ideal scenario, there should be:
- One centralized PKI/CA
- One certificate for securing NATS route/cluster connections
- One certificate for securing NATS client connections
- TLS route/cluster authentication should be enforced, so one TLS certificate per route/cluster peer
- TLS client authentication should be enforced, so one TLS certificate per client
And finally, we deploy NATS:
```bash
kubectl create -f nats.yml
```
Logs should be enough to make sure everything is working as expected:
```
$ kubectl logs -f nats-0
[1] 2017/12/17 12:38:37.801139 [INF] Starting nats-server version 1.0.4
[1] 2017/12/17 12:38:37.801449 [INF] Starting http monitor on 0.0.0.0:8222
[1] 2017/12/17 12:38:37.801580 [INF] Listening for client connections on 0.0.0.0:4242
[1] 2017/12/17 12:38:37.801772 [INF] TLS required for client connections
[1] 2017/12/17 12:38:37.801778 [INF] Server is ready
[1] 2017/12/17 12:38:37.802078 [INF] Listening for route connections on 0.0.0.0:6222
[1] 2017/12/17 12:38:38.874497 [TRC] 10.244.1.3:33494 - rid:1 - ->> [CONNECT {"verbose":false,"pedantic":false,"user":"nats_route_user","pass":"nats_route_pwd","tls_required":true,"name":"KGMPnL89We3gFLEjmp8S5J"}]
[1] 2017/12/17 12:38:38.956806 [TRC] 10.244.74.2:46018 - rid:3 - ->> [CONNECT {"verbose":false,"pedantic":false,"user":"nats_route_user","pass":"nats_route_pwd","tls_required":true,"name":"Skc5mx9enWrGPIQhyE7uzR"}]
[1] 2017/12/17 12:38:39.951160 [TRC] 10.244.1.4:46242 - rid:4 - ->> [CONNECT {"verbose":false,"pedantic":false,"user":"nats_route_user","pass":"nats_route_pwd","tls_required":true,"name":"0kaCfF3BU8g92snOe34251"}]
[1] 2017/12/17 12:40:38.956203 [TRC] 10.244.74.2:46018 - rid:3 - <<- [PING]
[1] 2017/12/17 12:40:38.958279 [TRC] 10.244.74.2:46018 - rid:3 - ->> [PING]
[1] 2017/12/17 12:40:38.958300 [TRC] 10.244.74.2:46018 - rid:3 - <<- [PONG]
[1] 2017/12/17 12:40:38.961791 [TRC] 10.244.74.2:46018 - rid:3 - ->> [PONG]
[1] 2017/12/17 12:40:39.951421 [TRC] 10.244.1.4:46242 - rid:4 - <<- [PING]
[1] 2017/12/17 12:40:39.952578 [TRC] 10.244.1.4:46242 - rid:4 - ->> [PONG]
[1] 2017/12/17 12:40:39.952594 [TRC] 10.244.1.4:46242 - rid:4 - ->> [PING]
[1] 2017/12/17 12:40:39.952598 [TRC] 10.244.1.4:46242 - rid:4 - <<- [PONG]
```
## Scale
**WARNING:** Due to the [Pod anti-affinity](#pod-anti-affinity) rule, for scaling up to _n_ NATS
instances, one needs _n_ available Kubernetes nodes.
```
kubectl scale statefulsets nats --replicas 5
```
Did it work?
```
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
svc/kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 1h
svc/nats ClusterIP None <none> 4222/TCP,6222/TCP,8222/TCP 4m
NAME READY STATUS RESTARTS AGE
po/nats-0 1/1 Running 0 4m
po/nats-1 1/1 Running 0 4m
po/nats-2 1/1 Running 0 4m
po/nats-3 1/1 Running 0 7s
po/nats-4 1/1 Running 0 6s
```
## Access the service
*Don't forget* that services in Kubernetes are only acessible from containers in the cluster.
In this case, we're using a [`headless service`](http://kubernetes.io/v1.1/docs/user-guide/services.html#headless-services).
Just point your client apps to:
```
nats:4222
```
<a id="pod-anti-affinity">
## Pod anti-affinity
One of the main advantages of running NATS on top of Kubernetes is how resilient the cluster becomes,
particularly during node restarts. However if all NATS pods are scheduled onto the same node(s), this
advantage decreases significantly and may even result in service downtime.
It is then **highly recommended** that one adopts [pod anti-affinity](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#inter-pod-affinity-and-anti-affinity-beta-feature)
in order to increase availability. This is enabled by default (see `nats.yml`).
================================================
FILE: nats.conf
================================================
listen: 0.0.0.0:4222
http: 0.0.0.0:8222
tls {
cert_file: "/etc/nats/tls/nats.pem"
key_file: "/etc/nats/tls/nats-key.pem"
timeout: 2
}
# Authorization for client connections
authorization {
user: nats_client_user
# ./util/mkpasswd -p T0pS3cr3t
password: nats_client_pwd
timeout: 1
}
# Cluster definition
cluster {
listen: 0.0.0.0:6222
# Disabled this because peer-auth requires real SANS DNS in certificate
#tls {
# cert_file: "/etc/nats/tls/nats.pem"
# key_file: "/etc/nats/tls/nats-key.pem"
# ca_file: "/etc/nats/tls/ca.pem"
# timeout: 5
#}
# Authorization for route connections
authorization {
user: nats_route_user
password: nats_route_pwd
timeout: 0.5
}
# Routes are actively solicited and connected to from this server.
# Other servers can connect to us if they supply the correct credentials
# in their routes definitions from above.
routes = [
nats://nats_route_user:nats_route_pwd@nats:6222
]
}
# logging options
debug: false
trace: true
logtime: true
# Some system overides
# max_connections
max_connections: 100
# maximum protocol control line
max_control_line: 512
# maximum payload
max_payload: 65536
# Duration the server can block on a socket write to a client. Exceeding the
# deadline will designate a client as a slow consumer.
write_deadline: "2s"
================================================
FILE: nats.yml
================================================
apiVersion: v1
kind: Service
metadata:
name: nats
labels:
component: nats
spec:
selector:
component: nats
clusterIP: None
ports:
- name: client
port: 4222
- name: cluster
port: 6222
- name: monitor
port: 8222
---
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
name: nats
labels:
component: nats
spec:
serviceName: nats
replicas: 3
template:
metadata:
labels:
component: nats
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: component
operator: In
values:
- nats
topologyKey: kubernetes.io/hostname
containers:
- name: nats
image: nats:1.0.4
args: [ "--config", "/etc/nats/config/nats.conf"]
volumeMounts:
- name: tls-volume
mountPath: /etc/nats/tls
- name: config-volume
mountPath: /etc/nats/config
ports:
- containerPort: 4222
name: client
- containerPort: 6222
name: cluster
- containerPort: 8222
name: monitor
livenessProbe:
httpGet:
path: /
port: 8222
initialDelaySeconds: 10
timeoutSeconds: 5
volumes:
- name: tls-volume
secret:
secretName: tls-nats-server
- name: config-volume
configMap:
name: nats-config
================================================
FILE: route_checker/main.go
================================================
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"net"
"net/http"
)
var (
lookupName = flag.String("lookup", "nats", "Lookup name")
server = flag.String("server", "http://localhost:8222", "NATS URL to query")
)
type routez struct {
RoutesCount int `json:"num_routes"`
}
func countInstancesInCluster(lookupName string) (int, error) {
_, srvRecords, err := net.LookupSRV("", "", lookupName)
if err != nil {
return 0, err
}
return len(srvRecords), nil
}
func main() {
flag.Parse()
// if we're the only instance in the cluster, we're good to go
// otherwise, we need to check if there are any routes established
// and if not, exit with error.
instances, err := countInstancesInCluster(*lookupName)
if err != nil {
log.Fatalf("There was an error while verifiying if this is the first instance in the cluster: %s\n", err.Error())
} else {
log.Printf("There are %d instances in the cluster.", instances)
}
if instances > 1 {
// query NATS monitoring endpoint
url := *server + "/routez"
log.Printf("Querying server %s..\n", url)
res, err := http.Get(url)
if err != nil {
log.Fatalf("There was an error while querying %s: %s\n", url, err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalf("There was an error while reading response: %s\n", err.Error())
}
var data routez
if err := json.Unmarshal(body, &data); err != nil {
log.Fatalf("There was an error while decoding response: %s\n", err.Error())
}
// if enough routes aren't established, exit with error
if data.RoutesCount < instances-1 {
log.Fatalf("There aren't enough routes established. Only %d out of %d.", data.RoutesCount, instances-1)
}
}
}
================================================
FILE: ssl.cnf
================================================
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = nats
gitextract_wobrug95/ ├── .gitignore ├── LICENSE ├── README.md ├── nats.conf ├── nats.yml ├── route_checker/ │ └── main.go └── ssl.cnf
SYMBOL INDEX (3 symbols across 1 files)
FILE: route_checker/main.go
type routez (line 17) | type routez struct
function countInstancesInCluster (line 21) | func countInstancesInCluster(lookupName string) (int, error) {
function main (line 30) | func main() {
Condensed preview — 7 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (24K chars).
[
{
"path": ".gitignore",
"chars": 18,
"preview": "*.pem\n*.csr\n*.srl\n"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 6367,
"preview": "# kubernetes-nats-cluster\nNATS cluster on top of Kubernetes made easy.\n\n**THIS PROJECT HAS BEEN ARCHIVED. SEE https://gi"
},
{
"path": "nats.conf",
"chars": 1432,
"preview": "listen: 0.0.0.0:4222\nhttp: 0.0.0.0:8222\n\ntls {\n cert_file: \"/etc/nats/tls/nats.pem\"\n key_file: \"/etc/nats/tls/nats-"
},
{
"path": "nats.yml",
"chars": 1555,
"preview": "apiVersion: v1\nkind: Service\nmetadata:\n name: nats\n labels:\n component: nats\nspec:\n selector:\n component: nats\n"
},
{
"path": "route_checker/main.go",
"chars": 1720,
"preview": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n)\n\nvar (\n\tlookupName = flag.Strin"
},
{
"path": "ssl.cnf",
"chars": 253,
"preview": "[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConst"
}
]
About this extraction
This page contains the full source code of the pires/kubernetes-nats-cluster GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 7 files (22.2 KB), approximately 5.9k tokens, and a symbol index with 3 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.