How to pass container ip as ENV to other container in docker-compose file How to pass container ip as ENV to other container in docker-compose file postgresql postgresql

How to pass container ip as ENV to other container in docker-compose file


You actually don't need to do any of this, since you're already using the links feature in Docker Compose. Just get rid of the PG_HOST variable and use the app-db hostname:

services: app-web:  restart: always  build: ./web  environment:    PG_PORT: 5432  ports:   - "8081:8080"  links:    - app-db

Since you included the app-db entry under links, you can simply use app-db as a hostname in your app-web container. Docker will set up a hostname mapping in the app-web container that resolves the app-db hostname to the database container's IP address.

You can verify that by running the following, which will try to ping the app-db container from the app-web container:

docker-compose exec app-web bash -c "ping app-db"

This should show output from the ping command showing the resolved IP address of the app-db container, for example like this:

PING app-db (172.19.0.2): 56 data bytes64 bytes from 172.19.0.2: icmp_seq=0 ttl=64 time=0.055 ms64 bytes from 172.19.0.2: icmp_seq=1 ttl=64 time=0.080 ms64 bytes from 172.19.0.2: icmp_seq=2 ttl=64 time=0.098 ms

Press ctrl+c to stop the ping command.

Like shown in the other answer, if you still want to pass in the hostname (which is probably a good idea, just in case you ever want to point to a different database), you can just use app-db as a value:

services: app-web:  restart: always  build: ./web  environment:    PG_HOST: app-db    PG_PORT: 5432  ports:   - "8081:8080"  links:    - app-db


You can use app-db as name instead of ip, docker will automatically determine what the right ip. As stated in the Docker docs: A container can always discover other containers on the same stack using just the container name as hostname.

So in your example you can use:

environment:    PG_HOST: app-db

Source:https://docs.docker.com/docker-cloud/apps/service-links/#discovering-containers-on-the-same-service-or-stack