Home > OS >  Connection between two docker containers in nextjs in getStaticProps function
Connection between two docker containers in nextjs in getStaticProps function

Time:08-21

I have two separate docker files, one for running nextjs on nginx web server and another for running Laravel on another nginx:

    services:

  frontendx:
    container_name: next_appx
    build:
      context: ./frontend
      dockerfile: Dockerfile
    restart: unless-stopped
    volumes:
      - ./frontend:/var/www/html/frontend
    networks:
      - app

      
  nginxy:
    container_name: nginxy
    image: nginx:1.19-alpine
    restart: unless-stopped
    ports:
      - '8080:80'
    volumes:
      - ./frontend:/var/www/html/frontend
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - frontendx
    networks:
      - app

and:

services:
  backendx:
    container_name: laravelx
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    ports:
      - '8000:8000'
    volumes:
      - ./:/var/www
      - enlive-vendor:/var/www/vendor
      - .//docker-xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
    depends_on:
      - dbx
    networks:
      - appx

  webserverx:
    image: nginx:alpine
    container_name: webserverx
    restart: unless-stopped
    tty: true
    ports:
      - "8090:80"
      - "443:443"
    volumes:
      - ./:/var/www
      - ./nginx/conf.d/:/etc/nginx/conf.d/
    networks:
      - appx

I can connect to the backend container through axios and address like : http://localhost:8090/api/my/api/address

but when I try to get data through getStaticProps I've got the ECONNREFUSED connection error:

  const res = await fetch(`http://localhost:8090/api/address`)

I tried to replace the localhost with container ip address like : 172.20.0.2 but I've got the 504 Gateway error.

CodePudding user response:

That's expected.

With axios, you're calling from the browser which is making the request from your host machine network.

But getStaticProps being a SSR function, is run inside your nextjs container. Therefore it must be able to find your backend in your app network.

Now by your setup, the frontend and backend apps are in different isolated networks and you can't connect them like this. But if you put them all your services in the same network, lets say your app(instead of appx) network, you can easily use docker dns:

  const res = await fetch(`http://webserverx/api/address`)

Docker knows how to resolve webserverx to your webserverx container.

  • Related