Exercise

  1. Create a new directory and develop an HTTP server that exposes the /ping endpoint on port 80 and responds with PONG.
To save time, you can use the Node.js example from the solution! :)
  1. In the same directory, create the Dockerfile that will be used to build the application image. This file should describe the following actions:
  • specify a base image
  • install the runtime corresponding to the chosen language
  • install application dependencies
  • copy the application code
  • expose the application’s listening port
  • specify the command to execute to start the server
  1. Build the image and tag it as pong:1.0

  2. Launch a container based on this image by publishing port 80 to port 8080 of the host machine

  3. Test the application

  4. Remove the container


Solution
  1. In this example, we chose Node.js

The following code is the content of pong.js (web server code)

pong.js
var express = require('express');
var app = express();
app.get('/ping', function(req, res) {
    console.log("received");
    res.setHeader('Content-Type', 'text/plain');
    res.end("PONG");
});
app.listen(80);

The package.json file contains the application’s dependencies (in this case, the expressjs library used for web application development in the NodeJs world).

{
  "name": "pong",
  "version": "0.0.1",
  "main": "pong.js",
  "scripts": {
    "start": "node pong.js"
  },
   "dependencies": {  "express": "^4.14.0" }
}
  1. A version of the Dockerfile that can be used to create an application image:
Dockerfile
FROM node:16-alpine
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 80
CMD ["npm", "start"]

Note: there are always several approaches to defining an application’s Dockerfile. For example, we could have started with a base image like ubuntu or alpine, and installed the nodejs runtime as in the example below:

Dockerfile
FROM alpine:3.14
RUN apk add -u npm
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 80
CMD ["npm", "start"]
  1. The following command builds the image from the previous Dockerfile:
docker image build -t pong:1.0 .
  1. The following command launches a container based on the pong:1.0 image and makes it accessible from port 8080 of the host machine:
docker container run --name pong -d -p 8080:80 pong:1.0
⚠️
Make sure the port isn’t already taken by another container or application. If it is, use port 8081 for example in the above command.
  1. To test the ping server, simply send a GET request to the /ping endpoint and verify that you get PONG in return:
curl localhost:8080/ping
  1. Remove the container using the following command:
docker rm -f pong