What is the best way to establish a connection between two services in a Docker-compose setup so that they are able to communicate with each

I'm new to Docker and facing challenges in connecting two separate services using docker-compose. I need to be able to write to a database and read from it. Additionally, each container should be able to ping the other one.

When I run

docker exec -ti node-app ping mongo
, everything works fine. However, when I try
docker exec -ti mongo ping node-app
, I encounter the following error:

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

Furthermore, upon starting docker-compose, I get the error message: 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('/'));
});


Answer №1

Initially, run the exec command on the container to verify if you are able to ping another container.

docker exec -i -t 665b4a1e17b6 bash

Next, within that container, attempt to ping the IP address of the other service.

ping 35.158.153.133

If the ping does not succeed, you may need to install it by referring to this link where the issue is being discussed.

If your ping works properly, then it indicates successful communication with the other service. You can then proceed with troubleshooting your own service.

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the operational structure of the Jasmine framework within the protractor environment

I'm a beginner in AngularJS and Protractor. After some research, I learned that Jasmine is the primary framework used by Protractor, but I'm struggling to grasp how it actually works. Can someone please provide some guidance on this? ...

What is the process for importing a module from node_modules?

Located within the node_modules directory is a subdirectory: data/lib/ This subdirectory contains the following files: index.js index.ts Data.js Data.ts How can we utilize this module with an import statement? I attempted to do so with the following c ...

The procedure for deleting npm and node package on a Mac system

Currently, I am struggling to completely remove the npm and node packages that I initially installed in order to replace them with the Homebrew version. Can someone provide me with guidance on how to successfully eliminate the package versions of node.js a ...

In what circumstances could my code encounter errors or failures?

Take a look at the code snippet below - exports.ticketList = function(req, res, next) { Ticket.find(function(err, data) { if (err) { //---- Error Handler ---- return next(err); } res.render('ticket ...

Error handling middleware for Node.js to catch and handle CORS issues in

Here is my code snippet for checking the origin header and allowing access by using express along with npm cors plugin: const app = express(); const cors = require('cors') var corsOptions = { origin: function (origin: any, callback: any) { ...

The application is unable to interpret parameterized queries when utilizing Express and PostgreSQL

Complete newbie over here, I'm attempting to revamp my endpoint in order to enable sorting the return table by multiple columns read in via variables 'sort_by' and 'order', which have default values. However, when running the test ...

Modifying the retrieval or storage object in mongodb

Here is the schema for my account: const account = new mongoose.Schema({ name: String, age: Number, coins: Number, phone: Number, sex: { type: String, default: 'f' } }, { timestamps: { ...

Generating socket.io functionality with the Express framework

After attempting the solution provided at Using socket.io in Express 4 and express-generator's /bin/www, I encountered an error message in the terminal on line 12 of /routes/messages.js: io.on('connection', function(socket){ TypeError: Canno ...

Terminate the execution of the process.exec function

Currently, I have a function in my code that is responsible for executing a specific process. Here's how it looks: static async runTest() { await process.exec(`start ${currentDir}/forward.py`); } runTest(); Here's the thing – once this Python ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

What are the necessary steps to launch Next.js without relying on Vercel's platform?

Looking to deploy a Next.js app, but not on Vercel. What is the process for deploying it? In the past, I would drag and drop the build folder from React to the server, but with Next.js I am unsure of which files need to be deployed and how. Note: I am ut ...

Guide to define maximum image size in Joi or Hapi

Currently, I am facing an issue with nodejs+mongodb. When uploading images on the front-end, the system restricts it to a maximum size of 50kb. However, I would like to increase this limit to 5MB so that larger images (around 1MB or 2MB) can also be upload ...

Node.js causing NPM error message to pop up consistently each time I launch the terminal

Hey there! Every time I open my terminal on my MacBook (OSX 10.15.4), I encounter this error message: /Users/anarenault/.nvm/v0.10.48/lib/node_modules/npm/bin/npm-cli.js:85 let notifier = require('update-notifier')({pkg}) ^^^^^^ ...

Guide to navigating to a different intent in a Google Action (Google Assistant Action)

Presently, I am developing an Action for the Google Assistant that prompts users to input their phone number. Following this prompt, another intent will repeat the phone number provided and inquire if it is correct. If the user indicates 'no', I ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Encountering an error with the Angular 2 SimpleChanges Object during the initial npm start process

Within my Angular 2 application, there exists a component that holds an array of objects and passes the selected object to its immediate child component for displaying more detailed data. Utilizing the "SimpleChanges" functionality in the child component a ...

Unable to obtain module reference

Something odd happened when I tried to use the underscore module in a specific file. Strangely enough, I have no issues using it in other files within the same project. It seems like the problem isn't with the underscore module itself. The beginning ...

Using a primary key in a relational database is crucial when utilizing an ORM tool such as Sequelize

As of now, I am involved in a nodejs project that involves utilizing Sequelize ORM to communicate with a Postgres database. When working with ORM like sequelize, should I utilize custom fields as primary keys in the database tables or stick with autogenera ...

What is causing the "unable to resolve dependency tree" error when using ng new newApp?

Struggling with creating a new Angular app using the command ng new app-name? When running the command, you may encounter the following error in the command line. Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depen ...