Problem scenario
You want to create a basic "Hello World" web page with Node.js running in a Docker container. How do you do this?
Solution
Prerequisite
Install Docker. If you need assistance, see this posting.
Procedures
1. Create three files in the same directory on a Linux server. A possible location would be the home directory of the user that will run the "docker" commands.
1.a. Dockerfile should have this as its content (which was modeled on what was here):
FROM node:argon
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 8080
CMD [ "npm", "start" ]
1.b. package.json should have this as its content (which was taken from https://nodejs.org/en/docs/guides/nodejs-docker-webapp/):
{
"name": "docker_web_app",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "First Last <first.last@example.com>",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.16.1"
}
}
1.c. server.js should have this as its content (which was mostly taken from https://nodejs.org/en/docs/guides/nodejs-docker-webapp/):
'use strict';
const express = require('express');
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello world. This is from Continual integration\n');
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
2. Run these two commands:
docker build .
docker images # Mentally identify in the output your new image.
3. Run this command but substitute 44444 with the port you want to access the Node.js web page on and replace abcd1234 with the image ID found above:
docker run -p 44444:8080 -d abcd1234 # where abcd1234 is an Image ID
4. Go to web browser. Go to x.x.x.x:49160 where x.x.x.x is the external IP address of the Docker host; to find this IP address you can go to the Docker host and run "icanhazip.com" if you have internet access on the host.