This post was first published in Digital Ocean blog post.
You may have heard the buzz around Kubernetes and noticed that many companies have been rapidly adopting it. Due to its many components and vast ecosystem it can be quite confusing to find where the path starts to learn it.
In this session, you will learn the basics of containers and Kubernetes. Step by step, we will go through the entire process of packaging a Node.js application into a Docker container image and then deploying it on Kubernetes. We will demonstrate scaling to multiple replicas for better performance. The end result will be a resilient and scalable Node.js deployment.
You will leave this session with sufficient knowledge of containerization, Kubernetes basics, and the ability to deploy highly available, performant, and scalable Node.js applications on Kubernetes.
Resources
View the slides for this talk
Transcript of The Commands and Manifests Used
Be sure to follow along with the recording for an explanation and replace kamaln7
with your own DockerHub username.
Node App
- Create an empty node package: npm init -y
- Install express as a dependency: npm install express
- index.js
const express = require('express')
const os = require('os')
const app = express()
app.get('/', (req, res) => {
res.send(`Hi from ${os.hostname()}!`)
})
const port = 3000
app.listen(port, () => console.log(`listening on port ${port}`))
Docker
- Dockerfile
FROM node:13-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
CMD node index.js
- Build the image:
docker build -t kamaln7/node-hello-app .
- Edit
index.js
and replace the wordHi
withHello
. - Re-build the image and notice Docker re-using previous layers:
docker build -t kamaln7/node-hello-app .
- Run a container to test it:
docker run --rm -d -p 3000:3000 kamaln7/node-hello-app
- Look at the running containers:
docker ps
- Stop the container:
docker stop CONTAINER_ID
- Push the image to DockerHub:
docker push kamaln7/node-hello-app
Kubernetes
- Get worker nodes:
kubectl get nodes
- Create a deployment:
kubectl create deployment --image kamaln7/node-hello-app node-app
- Scale up to 3 replicas:
kubectl scale deployment node-app --replicas 3
- Expose the deployment as a NodePort replica:
kubectl expose deployment node-app --port 3000
- Look at the newly created service (and the assigned port):
kubectl get services
- Grab the public IP of one of the worker nodes:
kubectl get nodes -o wide
- Browse to
IP:port
to test the service - Edit the service:
kubectl edit service node-app
- Replace
port: 3000
withport: 80
- Replace
type: NodePort
withtype: LoadBalancer
- Verify that the service was updated:
kubectl get service
- Run the above command every few seconds until you get the external IP address of the Load Balancer
- Browse to the IP of the Load Balancerhhuy