Reputation: 111
I am running a simple Nodejs application with 2 containers. A server container and a client. I have a setup so that when the client makes a request to the server, it streams some data back to the client, however when I try to make this request from the client, I receive the following error
connect ECONNREFUSED 127.0.0.1:8080
This is also the case when I use the containers IP address. Both containers are on the same network. I confirmed this with docker network inspect. When I make the same request via Postman, it works fine.
Here is my setup
Server Setup
Server Dockerfile
FROM node:12
EXPOSE 8080
WORKDIR /home/node/server
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "app.js"]
Server http function
http.createServer(function(request, response){
filePath = path.join("./serverdata", 'filename.txt');
var stat = fs.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
readStream.pipe(response);
})
.listen(port);
Client Setup
Client Dockerfile
FROM node:12
WORKDIR /home/node/client
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "capp.js"]
Client Get Function NB using the server container IP yielded same results
http.get('http://localhost:8080', (resp)=>{
let data = '';
resp.on('data', (chunk)=>{
data += chunk;
});
resp.end('end', ()=>{
console.log(data);
});
}).on("error", (err)=>{
console.log(err.message);
});
Docker Compose
version: "3.2"
services:
server-app:
build: ./serverClient
ports:
- 8080:8080
volumes:
- servervol:/serverdata
client-app:
build: ./clientClient
ports:
- 8081:8081
volumes:
- clientvol:/clientdata
depends_on:
- "server-app"
volumes:
servervol:
driver: local
clientvol:
driver: local
I have read a few posts proclaiming that the issue is with using localhost instead of the container IP, but I have tried both with no success. As mentioned, when done in Postman, it works fine; this leads me to think that the issue is with the client part. Any guidance is much appreciated.
Thanks
Upvotes: 3
Views: 7646
Reputation: 1275
Since you are using Docker Compose, by default (because you didn't specify network) your services share the same (default) network, and therefore you can use the name of the service instead of its IP address to communicate with it because Docker can figure out the IP address based on service name due to service name resolution.
And because of all that Docker magic, the only thing you need to change is the way you connect to server:
http.get('server-app:8080', (resp) => { ... })
Upvotes: 7