How to pass container ip as ENV to another container in dockerfile file
This is my docker-compose file:
version: '3.0'
services:
app-web:
restart: always
build: ./web
environment:
PG_HOST: $(APP_DB_IP)
PG_PORT: 5432
ports:
- "8081:8080"
links:
- app-db
app-db:
build: ./db
expose:
- "5432"
volumes:
- /var/lib/postgresql/data
I want to pass app-web ip app-db (Postgresql in this case) as ENV var so that it can connect to DB normally ... any idea on how to achieve it?
source to share
You can use app-db as name instead of ip, docker will automatically detect that the ip is correct. As stated in the Docker docs: A container can always discover other containers on the same stack using only the container name as the hostname.
So, in your example, you can use:
environment:
PG_HOST: app-db
source to share
You don't really need to do anything as you are already using the function links
in Docker Compose. Just get rid of the variable PG_HOST
and use the hostname app-db
:
services:
app-web:
restart: always
build: ./web
environment:
PG_PORT: 5432
ports:
- "8081:8080"
links:
- app-db
Since you included the entry app-db
in links
, you can simply use app-db
as the hostname in your container app-web
. Docker will set up a hostname mapping in the container app-web
, which resolves the hostname app-db
to the IP address of the database container.
You can test by doing the following, which will try to ping the container app-db
from the container app-web
:
docker-compose exec app-web bash -c "ping app-db"
This should show the output of the ping command showing the resolved IP address of the container app-db
, for example:
PING app-db (172.19.0.2): 56 data bytes
64 bytes from 172.19.0.2: icmp_seq=0 ttl=64 time=0.055 ms
64 bytes from 172.19.0.2: icmp_seq=1 ttl=64 time=0.080 ms
64 bytes from 172.19.0.2: icmp_seq=2 ttl=64 time=0.098 ms
Click ctrl+c
to stop ping command.
As shown in the other answer, if you still want to pass in the hostname (which is probably a good idea, just in case you want to specify a different database), you can simply 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
source to share