Initiate a request between two containers using an API call

I am currently running a node application, a front-end app using Next.js, and utilizing Redis and Postgres as databases. I have containerized Next.js and Node.js separately with Docker.

version: '3'
services:
  redis-server:
    image: 'redis'
    restart: always
  postgres-server:
    image: 'postgres:latest'
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
    ports:
      - "5433:5432"
    volumes:
        - ./docker/postgres/data/data/pg_hba.conf:/var/lib/postgresql/app_data/pg_hba.conf
        - ./src/db/sql/CREATE_TABLES.sql:/docker-entrypoint-initdb.d/CREATE_TABLES.sql
        - ./src/db/sql/INSERT_TO_TABLES.sql:/docker-entrypoint-initdb.d/INSERT_TO_TABLES.sql
        - ./src/db/sql/CREATE_FUNCTIONS.sql:/docker-entrypoint-initdb.d/CREATE_FUNCTIONS.sql
  node-app:
    build: .
    ports:
      - "4200:4200"
  client:
    build:
      context: ./client
      dockerfile: Dockerfile
    container_name: client
    restart: always
    volumes:
      - ./:/app
      - /app/node_modules
      - /app/.next
    ports:
      - 3000:3000

Currently when attempting to make a server-side rendering (SSR) request to localhost:4200, it fails due to the containers being separate. The system seems to be looking for the server on port 4200 within the client container when not a client-side request. I need guidance on how to reference the container directly, such as making an API request for SSR data like fetch('node-app/users').

Answer №1

When Docker-compose is used to configure services in a compose file, it automatically creates a network that connects all the services together. This allows containers to communicate with each other using the container names as hostnames, which are resolved to their corresponding IP addresses.

Therefore, when you need to access another container within the same network, simply use the container's name as the hostname in your code, like so:

fetch('http://node-app:4200/users')
.

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

Integrating Octokit middleware in Next.js for enhanced functionality

Currently, I am in the process of honing my skills by creating a GitHub app. In Octokit, there is a feature called createNodeMiddleware that caught my attention. However, integrating it with next.js seems to pose some challenges. My main issue right now re ...

When utilizing docker-compose, the Node application encounters difficulty connecting to Redis

Currently, I am setting up my development environment for a node app on Ubuntu using Docker. Below is the content of my docker-compose.yml: version: "2" services: redis: image: redis ports: - "6381:6379" volumes: - /var/lib/thinkl ...

In production, all Next.js API routes consistently return an "Interval Server Error," whereas in development, all routes operate smoothly without any issues

Every time I access any API route in my Next.js application in production, it results in a 500 "Internal Server Error". However, in development mode, all routes function smoothly and provide the expected output. https://i.stack.imgur.com/nPpeV.png https: ...

Ensure that the body parameter is not empty before proceeding with updating on MongoDB

I am currently working on updating a document in MongoDB using NodeJS with NextJS. The code snippet I have right now looks like this: import connect from "../../util/mongodb"; async function api(req, res) { if (req.method === "POST" ...

TypeError: The file extension ".json" is not recognized

Hello, Developers! command: => cross-env NODE_ENV=production node server.mjs Error node:internal/errors:464 ErrorCaptureStackTrace(err); ^ TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /home/windows/Docume ...

Troubleshooting a 400 error with the Stripe Webhook due to problems with the raw

After diligently following Stripes documentation on setting up webhooks and testing locally using their Stripe CLI, I have encountered a persistent issue. While I can successfully create events, I consistently receive a response of 400 POST. 2021-12-14 23: ...

Unable to utilize $regex for searching by _id in Mongoose version 6.6.3

My attempt to search data by id is as follows: _id: { $regex: '63a1bda46ec7f02cf5e91825', $options: 'i' }, }) .populate('user', 'name') .sort({ updatedAt: -1 }); Unfortunately, this r ...

Nginx Experiencing Persistent Failures Due to 'Signal' Issue

Currently, we have a DigitalOcean machine running on 5.15.0-100-generic #110-Ubuntu, hosting multiple NextJS frontends and a NodeJS backend through PM2 on various localhost ports. These projects are accessible via different subdomains of the main domain wi ...

CLI package enables exporting API facilities

I have a mono repository containing a CLI package (packages/cli) and a web application (apps/web). I want to utilize the public API of the CLI within the web app. The CLI package is packaged with tsup: export default defineConfig({ clean: false, dts: ...

Utilizing Docker for Next.js to leverage multi-core processing

I currently have my Next.js web application (SSG and SSR) deployed on a VPS with 6 CPU cores. The application is containerized using Docker and managed through a Docker Compose stack. It's running behind Traefik as a reverse-proxy. Here's an exa ...

Develop a higher-order authentication component for securing routes in Next.js

Currently, I am developing the authentication system for my Next.js application. I have set up a /api/auth/login endpoint to handle user login requests. Upon successful validation of user data, I generate an HTTP-only cookie containing a JWT token and send ...

Guide to building a MongoDB database object in conjunction with Next.js

I recently set up MongoDB in my Next.js application using a tutorial I found here: https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb. Within a file called mongodb-config.js, the configuration looks like this: import { MongoClient } ...

Module not found even after executing npm install within Docker container

I am currently in the process of Dockerizing a node application, but I'm encountering an issue when attempting to start the app using: docker-compose -f docker-compose -f docker-compose.override.yml An error message stating ** Error: Cannot find mod ...

How to efficiently initialize a Next.js app with Phusion Passenger while triggering the production build using a specific file?

In most cases, a Next.js application is launched by using the command npm run start after compiling it with npm run build. I am unable to start it using a command because my web server stack (Phusion Passenger) requires a specific startup script. https:// ...

Unable to access attributes of an unknown object (referencing 'Person')

I'm currently facing an issue when trying to POST data from my Next.js project to my MySQL database. Here is my frontend code: import React from 'react' import { useReducer, useEffect, useState } from 'react' import Axios from &ap ...

Securing your Next.js App with Express JWT Authentication

After setting up a /api/login endpoint to handle user login functionality, I created a login.js page to send form data to the login API. The login API authenticates user credentials stored in the database, generates a token, and saves it to a cookie. awai ...

What are the advantages of using global.mongoose for caching the MongoDB connection?

What is the reason for adding global.mongoose to cache the MongoDB connection? import mongoose from 'mongoose' let cached = global.mongoose if (!cached) { cached = global.mongoose = { conn: null, promise: null } } What is the purpose of this ...

I'm trying to establish a connection to MongoDB within the getStaticProps function in Next.js. Can anyone

Hello, I am a beginner in next.js and I have successfully rendered the home page on the server by populating the props object through a file named "products.json". Now, my next goal is to populate the props object in the function called getStaticProps usin ...

When attempting to install packages using npm init, Npm encounters errors and is

I encountered an error while attempting to install Next.js using the following command: $c:/Desktop/next: npm init next-app nextjs-blog The error message I received was: npm ERR! Could not install from "Dahal\AppData\Roaming\npm-cache&bs ...

Avoiding the installation of dependencies within npm packages, particularly in projects utilizing Next.js, Node

I've encountered a puzzling issue that seems to have no solution online. When I install npm packages, their dependencies are not automatically installed. This situation is resulting in numerous warnings appearing in the console, such as: Module not ...