I am not really sure I understand the question. You shouldn’t connect to a database in build time so when the images are built are usually not important only when the services start and in what order. If you have a special case which I can’t imagine now and you need to connect to a database during build, you need to implement a “wait” function which tries to connect to the DB in a loop until it succeeds and continues with the “main” process after that.
If you want postgres to run before the app runs, the solution is similar. depends_on can make sure the container starts before another container, but starting a container doesn’t mean a process inside the container is ready. If you have healthchecks, you can also try the long syntax of depends_on
and start a service when another service is considered healthy.