How do I dynamically add container ip in other Dockerfile ( I am running two container a) Redis b) java application . I need to pass redis url on run time to my java arguments
You should add your containers in the same network . Then at runtime you can use that name to refer to the container with its name. Container's name is the host name in the network. Thus at runtime it will be resolved as container's ip address.
Follow these steps:
First, create a network for the containers:
docker network create my-network
Start redis: docker run -d --network=my-network --name=redis redis
Edit java application's Dockerfile, replace -Dspring.redis.host=172.17.0.2"
with -Dspring.redis.host=redis"
and build again.
Finally start java application container: docker run -it --network=my-network your_image
. Optionally you can define a name for the container, but it is not required as you do not access java application's container from redis container.
Alternatively you can use a docker-compose
file. By default docker-compose
creates a network for running services. I am not aware of your full setup, so I will provide a sample docker-compose.yml
that illustrates the main concept.
version: "3.7"
services:
redis:
image: redis
java_app_image:
image: your_image_name
In both ways, you are able to access redis container from java application dynamically using container's hostname instead of providing a static ip.