How to build the docker image to run the websocket server in nodejs
First we need to create the websocket server using below code. We also need to create package.json file which should include the dependency - ws
// websocket-server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('A new client connected');
ws.on('message', function incoming(message) {
console.log('Received message:', message);
ws.send(`Echo: ${message}`);
});
ws.on('close', function close() {
console.log('Client disconnected');
});
});
console.log('WebSocket server running on ws://localhost:8080');
Create Dockerfile
Then you need to create a docker file as below.
# Dockerfile
FROM node:14
# Create app directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install app dependencies
RUN npm install
# Bundle app source
COPY . .
# Expose the WebSocket port
EXPOSE 8080
# Command to run the WebSocket server
CMD ["node", "main.js"]
Build Docker image
docker build -t websocket-server .
Start the container
docker run -p 8081:8080 websocket-server
Access the web socket server at ws://localhost:8081
Published on: Jun 14, 2024, 04:14 AM