How can I pass host IP address to Docker Compose file? How can I pass host IP address to Docker Compose file? docker docker

How can I pass host IP address to Docker Compose file?


Environment variables are an easy way to pass small bits of configuration like this in.

For this particular case I'd probably configure a URL and not the host's IP address. You could very reasonably want to deploy this application behind a load balancer; that load balancer might do TLS termination, so you can advertise an https: URL; your local IP address might not be directly reachable from your clients; you'd prefer to advertise a DNS name than an IP address if you have one.

In the Node code you can find environment variables in process.env:

const dev = {  ...env,  apiUrl: process.env.API_URL || 'http://localhost:3000/api'};

Then in your docker-compose.yml you can directly set that URL:

services:  front:    environment:      API_URL: http://10.20.30.40/api      # API_URL: https://example.com/myapp/api


What you want is called shell command substitution.
Something like: MYVAR=$(ip route get 1 | awk '{print $NF;exit}')

Unfortunately, command substitution is NOT supported in compose.
Compose supports only "static" shell variables aka shell variable expansion.
Your best bet would be to declare mandatory variable with an appropriate error message.

# requires for the var to be pre-declared in shellenvironment:  API_URL: ${API_URL:?"Variable API_URL must present in shell."}# alternatively you could provide some default valueenvironment:  API_URL: ${API_URL:-192.0.2.2}

Another solution may be to play with envsubst to edit your compose file in-place.
Check this answer for examples.


Also note that there is no such thing as "host's ip address" :)
It's kinda conventional and a pretty vague term.

"Primary IP" is an alias for "whatever your system uses when itoriginates traffic to the default route". In the absence of sourcephrases on that route, that's the first address of the interface used(more or less).

Thus, you need to be careful when writing your command to define "host's IP".
In simple network configurations this one is likely to work more or less fine.
ip route get 1 | awk '{print $NF;exit}'
But better check this discussion and make sure your eventual command returns what you expect.


By adding HOST_IP=http://host.docker.internal:PORT in environment variable of particular services like this

environment:  - HOST_IP=http://host.docker.internal:4001/

You can access the host ip inside the docker by accessing the environment variable in node js code like

var host_url=process.env.HOST_IP

NOTE: As you can access host ip only you need to add port manually at the end of url and it only works for the development server NOT for production.