I am working on a project with multiple microservices using Docker Compose. I have two services, matching_service and collaboration_service. The matching_service sends a POST request to the collaboration_service to create a room. However, the request fails with the following error:
Error creating room: request to http://localhost:4000/create-room failed, reason:
Response from createRoom: undefined
Response from createRoom: {
status: 500,
message: 'request to http://localhost:4000/create-room failed, reason: '
}
The matching_service can recieve post request but cannot send a GET or POST request. But the POST api works from postman and other backend services, except matching_service.
docker-compose.yml
matching-service:
build: ./backend/matching-service # Path to the directory containing the Dockerfile for building the backend/question-service image.
ports:
- 3002:3002
- 8080:8080
env_file:
- ./backend/matching-service/.env
depends_on:
rabbitmq:
condition: service_healthy
rabbitmq:
image: rabbitmq:3-management
ports:
- "5672:5672"
- "15672:15672"
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "status"]
interval: 5s
timeout: 10s
retries: 5
collaboration-service:
build: ./backend/collaboration-service # Path to the directory containing the Dockerfile for building the backend/user-service image.
ports:
- 4000:4000 # Maps port 3001 on the host to port 3001 in the container, making the app accessible on the host.
env_file:
- ./backend/collaboration-service/.env
matching_service
import fetch from "node-fetch";
import { v4 as uuidv4 } from "uuid";
const createRoom = async ({ participants }) => {
const url = "http://collaboration-service:4000/create-room"; // Using Docker service name
const requestBody = {
roomId: uuidv4(),
participants: participants,
};
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Server error: ${response.statusText}, ${errorText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error creating room:", error.message);
return { status: 500, message: error.message };
}
};
export { createRoom };
collaboration_service
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
dotenv.config();
const app = express();
app.use(express.json());
// Configure CORS to allow requests only from specific origins
const allowedOrigins = ['http://matching-service:3002']; // Origin of matching_service
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
const Room = require("./models/Room");
app.post("/create-room", async (req, res) => {
const { roomId, participants } = req.body;
try {
let existingRoom = await Room.findOne({ roomId });
if (existingRoom) {
return res.status(400).json({ message: "Room already exists" });
}
const newRoom = new Room({ roomId, participants });
await newRoom.save();
return res.status(201).json({ message: "Room created", room: newRoom });
} catch (err) {
return res
.status(500)
.json({ message: "Error creating room", error: err.message });
}
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));