In this article, there will be a more complicated project than that in the fourth one of this series.
1. AppOverview
We are going to make a small app by which we can record the number of visits.We intend to use Node
and Redis
,and set up something that looks like this right here.
2. App Server Code
You just copy these three files into your own project directory ,which I recommend to name visits
.The files ,plus the dir ,look really like those in last article of this column.Just go it over.
- the file level :
- visits
-- package.json
-- index.js
-- Dockerfile
- package.json
{
"dependencies":{
"express":"*",
"redis":"2.8.0"
},
"scripts":{
"start":"node index.js"
}
}
- index.js
const express= require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient();
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 8081");
})
- Dockerfile
FROM node:alpine
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
CMD ['npm', 'start']
Then ,we build the image,and use docker tag
to flag the image,in the case that we do not carry around the containerId here and there.
docker build -t justinwins/visits:latest .
docker run justinwins/visits:latest
3. Docker Compose
As we run the image, we see darn straightforward error message.
> @ start /app
> node index.js
Listening on 8081
events.js:173
throw er; // Unhandled 'error' event
^
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1083:14)
Obviously, that happens because there is no Redis service running in the container, the same container,i mean.
In other words, even though we start up a redis image now from another terminal , that happens still .The root cause we start the two containers separately ,and they do not connect to each other as we may have expected .
This diagram just illustrates that:
To tackle this problem,we at this point have two options,still on the diagram:
Of the two options ,we prefer option2 since option1 involves pretty a lot of extra work and option1 is a proven encapsulated tool .Basically, very few people make use of Option2 in industry and I have seen no one has done .Let’s focus on Option2.
In short,docker compose
do like this:
Personally, I think Docker compose
especially makes networking a very easy thing as it automatically connects containers ,and keeps the connection between them.