5 Docker Compose with Multiple Local Containers


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.

  1. the file level :
- visits
	-- package.json
	--  index.js
	-- Dockerfile
  1. package.json
{
	"dependencies":{
		"express":"*",
		"redis":"2.8.0"
	},
	
	"scripts":{
		"start":"node index.js"
	}
}
  1. 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");
}) 
  1. Dockerfile
FROM node:alpine

WORKDIR '/app'

COPY package.json .
RUN npm install
COPY . .

CMD ['npm', 'start']

Then ,we build the image,and use docker tagto 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.

4.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值