Node.js Url Routing Example Using Docker

Simple ways to use URI to direct requests!

Let us get on with the implementation of the above diagram.

Dockerfile

The Dockerfile looks like this.

FROM node:4.4
MAINTAINER Sreeprakash Neelakantan
EXPOSE 8080
COPY server_uri.js .
CMD node server_uri.js

JavaScript File

server_uri.js looks like this.

const http = require('http');
const os = require('os');
const url = require('url');
var handleRequest = function(req, res) {if(req.url === '/' ) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write("<h1>Welcome to Tea & Coffee Shop</h1>");
res.write("<h2>Hostname: " + os.hostname() + "</h2>");
res.end();
}
if(req.url === '/tea' ) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write("<h1>Welcome to Tea & Coffee Shop</h1>");
res.write("<h2>Here is your hot cup of <b>TEA</b><br><br>from: " + os.hostname() + "</h2>");
res.end();
}
if(req.url === '/coffee' ) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write("<h1>Welcome to Tea & Coffee Shop</h1>");
res.write("<h2>Here is your hot cup of <b>COFFEE</b><br><br>from: " + os.hostname() + "</h2>");
res.end();
}
res.writeHead(404);
res.write("<h1>Welcome to Tea & Coffee Shop</h1>");
res.write("<h2>Sorry! We only serve tea or coffee. Not: <b>"+req.url+ "</b><br><br>from: " + os.hostname() + "</h2>");
res.end();
}
const server = http.createServer(handleRequest);
console.log("Listening on port 8080\n");
server.listen(8080);

Build Docker Image

Build the image like this.

docker build -t temp -f Dockerfile .

Run Docker Container

Run a container using the above image.

docker run -d --name temp -p 8081:8080 --rm temp

Testing

Let us now check the routing using curl

curl localhost:8081<h1>Welcome to Tea & Coffee Shop</h1><h2>Hostname: 672b9575f0a4</h2>curl localhost:8081/tea<h1>Welcome to Tea & Coffee Shop</h1><h2>Here is your hot cup of <b>TEA</b><br><br>from: 7cfb69266e2f</h2>curl localhost:8081/coffee<h1>Welcome to Tea & Coffee Shop</h1><h2>Here is your hot cup of <b>COFFEE</b><br><br>from: 7cfb69266e2f</h2>curl localhost:8081/asdasd<h1>Welcome to Tea & Coffee Shop</h1><h2>Sorry! We only serve tea or coffee. Not: <b>/asdasd</b><br><br>from: 7cfb69266e2f</h2>curl -I localhost:8081/asdasd
HTTP/1.1 404 Not Found
Date: Sat, 24 Nov 2018 10:54:23 GMT
Connection: keep-alive

Using the browser

Thanks for your time. Do follow for more such tiny demos!

Sreeprakash Neelakantan

Written by

AWS Certified DevOps Engineer & Solutions Architect Professional — Docker | Kubernetes | DevOps — Trainer | Running | Swimming | Cycling

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade