I managed to create and deploy a k8s cluster with minikube, running 4 replicas of a simple hello-world node.js app, using the following configuration.
Dockerfile for the app:
FROM ubuntu:latest
RUN apt-get update
RUN apt-get -qq update
RUN apt-get install -y nodejs npm
# TODO could uninstall some build dependencies
# debian installs `node` as `nodejs`
RUN update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10
COPY package.json package.json
RUN npm install
COPY . .
CMD ["node", "app.js"]
k8s Deployment yml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: node-deployment
labels:
app: node-app
spec:
replicas: 4
selector:
matchLabels:
app: node-app
template:
metadata:
labels:
app: node-app
spec:
containers:
- name: node-app
image: my-repo/ubuntu-node:sectry
ports:
- containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: node-service
labels:
app: node-app
spec:
type: NodePort
ports:
- port: 3000
protocol: TCP
selector:
app: node-app
My question is how can add an nginx container for it? I know k8s cluster already load-balancing, but I really wish to use NGINX features.
I guess you want to use nginx as a reverse proxy to your Node.js app. If it is the case, you can use one of the following ways to achieve it.
Option 1
Build nginx and your node.js app into one Docker image. In this image, configure nginx as a reverse proxy and forward the request to your node.js app. For example, the following nginx configure forwards the request to port 3000 in the same container.
server {
listen 80;
server_name localhost;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:3000;
}
}
You can then deploy this image to k8s cluster, and create a service for it.
Option 2
ClusterIP
as the service type for node.js image, and LoadBalancer
for nginx image.To test it on minikube, Option 1 is easier. Option 2 is recommended for a production k8s cluster.
I would add third option : use an Ingress Controller https://github.com/nginxinc/kubernetes-ingress.
It will create all this features that you are looking for and built in on K8s.