Let’s assume we have two backend apps, where backend_for_frontend
needs to fetch some data from api
.
If both apps are run in docker or api
runs in docker and backend_for_frontend
runs locally, backend_for_frontend
can use http://host.docker.internal:3001/api
address to connect to api.
If both apps are run locally(not in docker) then backend_for_frontend
needs to use http://127.0.0.1:3001/api
for api
connection.
Issue is that when we switch running api
between docker or locally, we need to use different ip for backend_for_frontend
that needs to be manually changed because backend_for_frontend
doesn’t know how we run api
.
Is there a way to resolve this ip somehow automatically or use ip as env variable that will work in any case? Basically I want to run backend_for_frontend
and api
in any combination, while connection url for backend_for_frontend
still can be resolved not by hand.
docker.compose
example:
services:
api:
ports:
- 3001:3001
backend_for_frontend:
ports:
- 3002:3002
3
Answers
Hello it’s just the same as if you don’t dockerize, call them by your port and socket
Your first api will call by : http://localhost:3001
And the seconds will be
http://localhost:3002
P.s you can use a network so they are in an internal network
That’s all
It can be achieved via using hostname instead of using direct IP address to access the API.
this will give flexibility to use hostname regardless of API running locally or on Docker.
for example, it can be used http://api:3001/api as the base URL for the API in backend_for_frontend, and then set up Docker Compose file to define a hostname for the api service:
That’s a very common configuration scenario and you’ll usually solve it by setting an environment variable in
backend_for_frontend
to the URL of the API.Let’s call the environment variable
API_URL
. Then you can doThen, when you run the API locally, you’d change it to
http://host.docker.internal:3001/
.You’ll need to change your
backend_for_frontend
code to fetch the URL from the environment variable. There’s no universal way of doing it and it depends on what language yourbackend_for_frontend
is coded in.If you have an URL that you want to be the default, you can add an
ENV
statement to thebackend_for_frontend
Dockerfile to set it. Then you only need to specify it in your docker-compose file when you want to override it.