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 to app-web the ip of app-db (Postgresql in this case) as ENV var so it can connect to the DB smoothly... any idea on how to achieve it?
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 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With