Sami
Sami

Reputation: 129

Fetch data from gatServerProps of NextJs app when another api server is also running in localhost

According NextJs Documentations:

You should not use fetch() to call an API route in getServerSideProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!

So we cannot use NextJs built-in APIs in getStaticProps or getServerSidePropsbut when I'm going to use another API service that is based on Laravel Framework as the back server and fetch it by Axios on the getServerSideProps function, I get Error: connect ECONNREFUSED 127.0.0.1:8080 error. It should also be noted that everything is fine if the API server is addressed out of our development machine. In Other words, It will face when it's the development environment and both Laravel backend server and NextJs front-end server locate at localhost.

Could you help me out finding a solution for this problem?

Upvotes: 2

Views: 1401

Answers (2)

porloscerros Ψ
porloscerros Ψ

Reputation: 5098

So, as @tperamaki's answer already mentions: "When using localhost or 127.0.0.1 inside a docker container, that points to that docker container only, not the host computer."

You can use the ip of your machine in your local network. By example, 196.168.0.10:8080 instead 127.0.0.1:8080.

But you also can connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. In your case just add the port where the othe container is listening:

http://host.docker.internal:8080

In this section of the documentation Networking features in Docker Desktop for Mac, they explain how to connect from a container to a service on the host. Note that a mac is mentioned there, but I tried it on a linux distro and it also works (also in this other answer it is mentioned that it works for windows).

Upvotes: 1

tperamaki
tperamaki

Reputation: 1028

When using localhost or 127.0.0.1 inside a docker container, that points to that docker container only, not the host computer.

There are two pretty easy solutions.

  1. Create a docker network, add both containers to that, and use container name instead of ip (https://www.tutorialworks.com/container-networking/)
  2. Use host networking for this container: https://docs.docker.com/network/host/

Edit: Added a link for a tutorial on how to create and use docker networks

Upvotes: 1

Related Questions