Create working dir and change to it:
$ mkdir visits
$ cd visits
Create package.json file for NodeJS:
$ cat package.json
{
"dependencies": {
"express": "*",
"redis": "2.8.0"
},
"scripts": {
"start": "node index.js"
}
}
Create an index.js file for NodeJS which uses Express and Redis:
$ cat index.js
const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient({
host: 'redis-server',
port: 6379
});
client.set('visits', 0);
app.get('/', (req, res) => {
client.get('visits', (err, visits) => {
res.send('Number of visits is ' + visits);
client.set('visits', parseInt(visits) + 1);
});
});
app.listen(8081, () => {
console.log('Listening on port 8081');
});
Create Dockerfile for NodeJS app:
$ cat Dockerfile
FROM node:alpine
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY ./index,js .
CMD ["npm", "start"]
Create docker-compose file which will start the Redis and NodeJS app:
$ cat docker-compose.yml
version: '3'
services:
redis-server:
image: 'redis'
node-app:
restart: always
build: .
ports:
- "4001:8081"
Bring up the containers:
$ docker-compose up -d
Test the application by going to the http://localhost:4001/ using the browser$ docker-compose down