0

I'm using docker compose and one service runs NGINX. Inside its configuration I need the IP address of another service/container. I already found this which describes how to use env variables in nginx config files. However, the problem I have now is how to get an IP address of a service inside another service?

version: "3.9"
services:
  webserver: 
  environments:
     - API_HOST: api
  ...

  api: 
    ...

This is what I tried, but this will not result in an environment variable with an IP address. The contents of the $API_HOST will just be api.

So my question is, how can I do this. In that post I mention above there is also a solution to have a custom entrypoint script, so I can execute commands on startup inside the nginx container! Any suggestions?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • 3
    Can't you use the service name in your nginx config? Docker should resolve the name to the container IP. However, if you definitely need the IP, you can assign your api service a static IP and pass it as environment variable – dsax7 Apr 17 '23 at 16:39
  • I tried to use the service name, but nginx didn't like that. But maybe you're right with using a static ip. Thnx for the suggestion! – Jeanluca Scaljeri Apr 17 '23 at 17:18
  • 1
    Steps on how tos: https://stackoverflow.com/questions/39493490/provide-static-ip-to-docker-containers-via-docker-compose – Suchandra T Apr 17 '23 at 17:35
  • 1
    Weird, that the service name did not work. I have also used nginx with `docker-compose` and haven't had a problem. Maybe you can post your nginx problem as a separate question. – dsax7 Apr 17 '23 at 17:35
  • Yes it can indeed work, for example, this works: ` proxy_pass http://api:3000;` but this doesn't: `allow api;` – Jeanluca Scaljeri Apr 17 '23 at 17:50
  • 1
    I see, I guess as a workaround you could allow `172.18.0.0/16` which is all containers in the network – dsax7 Apr 17 '23 at 18:24
  • 1
    haha, that is exactly what I'm trying out right now. I noticed that the network uses 172.0.0.0/8. Just to be on the safe side! Using static ip addresses works too btw. I followed the steps from the link from @SuchandraT . But is not an ideal solution for me. Thanks a lot! – Jeanluca Scaljeri Apr 17 '23 at 19:35

0 Answers0