WebSocket Deployment — Complete Guide
In this tutorial, you will learn about WebSocket Deployment. We cover key concepts, practical examples, and best practices to help you master this topic.
Deploying WebSocket applications requires special considerations for long-lived connections, sticky sessions, graceful shutdown, and horizontal scaling. Unlike HTTP, WebSocket connections persist across deployments.
What You'll Learn
- Docker containerization for WebSocket
- Kubernetes deployment with horizontal scaling
- Cloud provider WebSocket support
- Process management with PM2
- Monitoring and logging strategies
Why It Matters
WebSocket deployments fail when standard HTTP deployment practices are applied. Long-lived connections, state management, and graceful shutdown require specific configuration.
Real-World Use
Discord deploys WebSocket behind Envoy proxy. Slack uses AWS ALB with sticky sessions. Trading platforms use Kubernetes with dedicated node pools for WebSocket servers.
flowchart TD
DNS[DNS] --> LB[Load Balancer]
LB --> Ingress[Kubernetes Ingress]
Ingress --> Service[WebSocket Service]
Service --> Pod1[Pod 1: WS Server]
Service --> Pod2[Pod 2: WS Server]
Service --> Pod3[Pod 3: WS Server]
Pod1 --> Redis[Redis Pub/Sub]
Pod2 --> Redis
Pod3 --> Redis
Redis --> Shared[Shared State]
Teacher Mindset
Containerize your WebSocket server. Use a process manager for Node.js. Configure health checks. Implement graceful shutdown that drains connections. Use a pub/sub Adapter for horizontal scaling.
Code Examples
# Example 1: Dockerfile for WebSocket server
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s \
CMD wget --no-verbose --tries=1 --spider \
http://localhost:8080/health || exit 1
CMD ["node", "server.js"]
# Example 2: Kubernetes deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: ws-server
spec:
replicas: 3
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: ws-server
template:
metadata:
labels:
app: ws-server
spec:
containers:
- name: ws-server
image: ws-server:latest
ports:
- containerPort: 8080
name: websocket
env:
- name: REDIS_URL
value: redis://redis-service:6379
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 15
periodSeconds: 20
---
apiVersion: v1
kind: Service
metadata:
name: ws-service
spec:
selector:
app: ws-server
ports:
- port: 80
targetPort: 8080
type: ClusterIP
// Example 3: Graceful shutdown
const server = require('http').createServer();
const wss = new WebSocket.Server({ server });
function gracefulShutdown() {
console.log('Received shutdown signal');
// Stop accepting new connections
server.close(() => {
console.log('HTTP server closed');
process.exit(0);
});
// Notify existing clients
wss.clients.forEach((ws) => {
ws.send(JSON.stringify({ type: 'shutdown', message: 'Server restarting' }));
ws.close(1001, 'Server restart');
});
// Force close after timeout
setTimeout(() => {
console.log('Force closing remaining connections');
wss.clients.forEach((ws) => ws.terminate());
process.exit(1);
}, 10000);
}
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
Common Mistakes
- Not implementing graceful shutdown for WebSocket connections
- Setting readiness probes too aggressively, killing servers during normal restarts
- Not configuring maxSurge=0 for zero-downtime rolling updates
- Missing health check endpoints for load balancer monitoring
- Not configuring connection draining during scale-down events
Practice
- Dockerize your WebSocket server with health checks.
- Create a Kubernetes deployment with 3 replicas.
- Implement graceful shutdown with connection draining.
- Set up readiness and liveness probes.
- Challenge: Configure horizontal pod autoscaling based on WebSocket connection count.
FAQ
Mini Project
Deploy your WebSocket server in a Kubernetes cluster with: Docker image with health checks, Deployment with 3 replicas and rolling update, Service with ClusterIP, Ingress with sticky sessions, Redis adapter for state sharing, and graceful shutdown with client notification.
What's Next
Next, you will build a complete WebSocket project integrating all concepts.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro