Exercise
- 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! :)
- 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
-
Build the image and tag it as pong:1.0
-
Launch a container based on this image by publishing port 80 to port 8080 of the host machine
-
Test the application
-
Remove the container
Solution
- 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" }
}
- 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"]
- The following command builds the image from the previous Dockerfile:
docker image build -t pong:1.0 .
- 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.
- 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
- Remove the container using the following command:
docker rm -f pong