Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't send request during build time in next.js with docker?

I'm trying to send a request in my getStaticProps function to my backend api from another docker container. However, even though the api url is written correctly, the static page still is not created. This is because for the static page to be built, the backend should be up already, and because it is build-time the other container is not up yet and waits for the build to be finished and the build can not be finished without the backend.

So what's the solution to this approach? I tried setting the depends_on value to my other container, still doesn't work. what solution would you suggest?

like image 928
Dasto Avatar asked Apr 19 '21 12:04

Dasto


2 Answers

There are 2 solutions I can think of.

Apparently, the Next.js build fails because the service it is querying is not running. Thus why not build and start the service it depends on explicitly and build the rest like this.

docker-compose build some_services
docker-compose up -d some_services
docker-compose build the_rest

This way the Next.js app will be able to make the request. Please keep in mind that You still need to configure the ports and networks correctly. Pretty sure this will resolve the issue.

A more 'fancy' solution would be using build-time networks which are added in the later versions, 3.4+ if I am not mistaken.

docker-compose.yml

build:
    context: ./service_directory
    network: some_network
   

For more details please see Docker-compose network

like image 121
Davit Avatar answered Oct 28 '22 12:10

Davit


Running a new service that depends whether another service is up or not is a tricky part of docker orchestration. Keep in mind that even with Healthcheck, it doesn't guarantee you database is ready before the next stage. depends_on is not going to be really helpful, because it just determine the order of running service. docker documentation:

depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. What docker doc suggests is to write a wait-for-it script or [wait-for][2] and run it after or before depends-on. For example:

build: next_service
command: sh -c './wait-for db:5432 -- npm start'
depends_on:
  - db

And of course, you explicitly run separate docker-compose command but that loses the point of docker orchestration.

like image 2
Dory Nguyen Avatar answered Oct 28 '22 12:10

Dory Nguyen