Visconte
Visconte

Reputation: 139

How could I create connection between two services in docker-compose so that they can ping each other?

I am novice in docker and struggle with connecting two separate services using docker-compose. I need to be able to write in database and read from it. Also, it is necessary to ping from each container the other one.

I do docker exec -ti node-app ping mongo and everything is okay. I do docker exec -ti mongo ping node-appand get this error:

OCI runtime exec failed: exec failed: container_linux.go:348: starting container process caused "exec: \"ping\": executable file not found in $PATH": unknown

Also, when I start docker-compose I have the following error: Server running... node-app | { MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 172.21.0.3:27017]

docker-compose

version: '3'
services:
  app:
    container_name: node-app
    restart: always
    build: .
    ports:
      - '80:3000'
    networks:
      - net
  mongo:
    container_name: mongo
    image: mongo
    restart: always
    ports:
      - 27017:27017
    networks:
      - net
networks:
  net:
    driver: bridge

Dockerfile

FROM node:10

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 35.158.153.133/80 # my aws public ip address

CMD ["npm", "start"]

index.js

mongoose
  .connect(
    'mongodb://mongo:27017/mongo',
    { useNewUrlParser: true }
  )
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));

const Item = require('./models/Item');

app.get('/', (req, res) => {
  Item.find()
    .then(items => res.render('index', { items }))
    .catch(err => res.status(404).json({ msg: 'No items found' }));
});

app.post('/item/add', (req, res) => {
  const newItem = new Item({
    name: req.body.name
  });

  newItem.save().then(item => res.redirect('/'));
});


Upvotes: 0

Views: 306

Answers (2)

Visconte
Visconte

Reputation: 139

I just find the answer. mongo container doesn't have ping. So I entered this container and did apt update and apt install iputils-ping. Then I was able to ping containers from both sides.

Upvotes: 0

Muzi Jack
Muzi Jack

Reputation: 798

first exec the container and check if you can ping the other container

docker exec -i -t 665b4a1e17b6 bash

then in that container ping the ip address of the other service

ping 35.158.153.133

if ping doesn't work, you gonna have to install it, use this link they are already discussing it.

if your ping works then you know you can contact the other service. then you can start troubleshooting your service.

Upvotes: 0

Related Questions