Building a Simple Chat Application with Node.js and Kubernetes
Building a Simple Chat Application with Node.js and Kubernetes
In this blog post, we'll embark on a journey to create a straightforward yet powerful chat application using Node.js and Kubernetes. Whether you're a seasoned developer or new to the world of web development, this tutorial will provide you with valuable insights into building scalable, real-time applications.
Thanks for reading Olusola’s Substack! Subscribe for free to receive new posts and support my work.
Why Node.js and Kubernetes?
Node.js is a runtime environment that allows developers to write server-side code using JavaScript. It's designed for building scalable network applications, making it an excellent choice for a chat application that requires real-time data transmission.
Kubernetes, on the other hand, is an open-source platform for automating deployment, scaling, and operations of application containers across clusters of hosts. It ensures our chat application can handle growth in users and data volume efficiently.
Getting Started
Before diving into the code, ensure you have the following installed:
- Node.js
- Docker
- Kubernetes (Minikube for local development or a cloud provider if you're deploying it externally)
Step 1: Setting Up the Node.js Server
1. Initialize a New Node.js Project:
Create a new directory for your project and initialize a Node.js application:
mkdir chat-app
cd chat-app
npm init -y
2. Install Dependencies:
We'll use `express` for our server framework and `socket.io` for real-time communication.
npm install express socket.io
3. Create the Server:
Create a file named `server.js` and add the following code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.get('/', (req, res) => {
res.send('<h1>Hello World!</h1>');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This server listens for connections and broadcast chat messages to all connected clients.
Step 2: Creating the Frontend
1. Create a Basic HTML Page:
Inside your project directory, create a `public` folder and add an `index.html` file with a basic chat interface.
<!DOCTYPE html>
<html>
<head>
<title>Chat App</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
document.getElementById('messages').appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>
2. Serve the HTML Page:
Modify the server to serve this HTML file:
app.use(express.static('public'));
Step 3: Dockerizing the Application
1. Create a Dockerfile:
In your project root, create a `Dockerfile`:
FROM node:20-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
2. Build and Run the Docker Image:
docker build -t chat-app .
docker run -p 3000:3000 chat-app
Step 4: Deploying to Kubernetes
1. Create a Deployment Configuration:
Create a `deployment.yaml` file for your Kubernetes deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: chat-app
spec:
replicas: 2
selector:
matchLabels:
app: chat-app
template:
metadata:
labels:
app: chat-app
spec:
containers:
- name: chat-app
image: chat-app
ports:
- containerPort: 3000
2. Deploy to Kubernetes:
kubectl apply -f deployment.yaml
3. Scale Your Application:
Kubernetes allows you to easily scale your application based on demand:
kubectl scale deployment/chat-app --replicas=4
Conclusion
Congratulations! You've just created a simple yet scalable chat application using Node.js and Kubernetes. This setup allows you to handle real-time data effectively and scale your application to meet user demand. Experiment with the code, try adding new features, and see how Kubernetes makes managing your application's infrastructure easier.
This tutorial merely scratches the surface of what's possible with these powerful technologies. Continue exploring and building to become more proficient in creating real-time, scalable web applications.
You can buy my e-book on building node.js and kubernetes apps on selar => Node.js and Kubernetes or gumroad => Node.js and Kubernetes
Thanks for reading Olusola’s Substack! Subscribe for free to receive new posts and support my work.
Originally published on substack
Enjoyed this?
Subscribe to get new essays in your inbox.