Dynamically add docker container ip in Dockerfile ( redis)

后端 未结 2 1570
一个人的身影
一个人的身影 2021-01-27 11:50

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

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 12:25

    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:

    1. First, create a network for the containers: docker network create my-network

    2. Start redis: docker run -d --network=my-network --name=redis redis

    3. Edit java application's Dockerfile, replace -Dspring.redis.host=172.17.0.2" with -Dspring.redis.host=redis" and build again.

    4. 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.

提交回复
热议问题