1

I've looked at many stackoverflow answers but couldn't find a solution to my problem, so I apologise if it seems similar to other questions.
I have a docker compose file which needs to connect to a local database sitting on port 5555. I need to be able to set an env var in the docker compose file that will translate to my host machines IP address.
Something like

environment:
  - db_uri=postgres://(HOST_IP):5555/db_name

How can I do this?

Oliver Robie
  • 818
  • 2
  • 11
  • 30
  • You'd need to set the environment variable outside Docker Compose space, but the linked question discusses the standard ways to find it. On non-Linux host Docker provides a DNS name for you. I'd avoid host networking if you can (for all the top answer to that question promotes it), it disables many of the standard Docker features. – David Maze Feb 10 '20 at 11:25

2 Answers2

1

I think you should create two containers with the same network, then you can call the database URL directly.

refers: https://runnable.com/docker/docker-compose-networking

LTNB
  • 111
  • 2
0

This can be done in 2 steps -

  1. Define HOST_IP as a variable in the docker compose file, using the ${} notation as follows:

db_uri=postgres://${HOST_IP}:5555/db_name

  1. Pass the dynamic variable - HOST_IP to compose file, either through .env file in the same directory or through export command.

.env file example:

HOST_IP=192.168.1.100

export command example:

export HOST_IP=192.168.1.100

More information:

Dynamic variables in docker compose file: https://serversforhackers.com/c/div-variables-in-docker-compose

Get the IP address of a host:

Which terminal command to get just IP address and nothing else?

Gopinath
  • 4,066
  • 1
  • 14
  • 16
  • This would work, however I'm looking for a way to be able to find the HOST_IP on whatever machine I'm using, so I don't want to hard code the IP address because then it could potentially change on every machine – Oliver Robie Feb 10 '20 at 12:06
  • Hi Oliver, Please refer the link - https://stackoverflow.com/questions/8529181/which-terminal-command-to-get-just-ip-address-and-nothing-else/26694162#26694162 for details on finding IP address on all hosts. – Gopinath Feb 10 '20 at 15:49