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
Currently I am manually checking the redis ip and copying it in Dockerfile. and later creating new image using redis ip for java application.
docker run --name my-redis -d redis
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-redis
IN Dockerfile (java application)
CMD ["-Dspring.redis.host=172.17.0.2", "-jar", "/apps/some-0.0.1-SNAPSHOT.jar"]
Can I use any script to update the DockerFile or can use any environment variable.
you can assign a static ip address to your dokcer container when you run it, following the steps:
1 - create custom network:
2 - run the redis container to use the specified network, and assign the ip address:
by then you have the static ip address
172.17.0.2
formy-redis
container, you don't need to inspect it anymore.3 - now it is possible to run the java appication container but it must use the same network:
of course you can optimize the solution, by using env variables or whatever you find convenient to your setup.
More infos can be found in the official docs (search for
--ip
):Edit (add docker-compose):
I just find out that it is also possible to assign static ips using docker-compose, and this answer gives an example how.
This is a similar example just in case:
official docs: https://docs.docker.com/compose/networking/
hope this helps you find your way.
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 defaultdocker-compose
creates a network for running services. I am not aware of your full setup, so I will provide a sampledocker-compose.yml
that illustrates the main concept.In both ways, you are able to access redis container from java application dynamically using container's hostname instead of providing a static ip.