在Dockerfile中动态添加Docker容器ip(redis) [英] Dynamically add docker container ip in Dockerfile ( redis)
问题描述
如何在其他Dockerfile中动态添加容器ip(我正在运行两个容器a)Redis b)java应用程序。
我需要在运行时将redis url传递给我的java参数
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
当前,我正在手动检查redis ip并将其复制到Dockerfile中。然后使用redis ip for Java应用程序创建新映像。
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应用程序)
IN Dockerfile (java application)
CMD ["-Dspring.redis.host=172.17.0.2", "-jar", "/apps/some-0.0.1-SNAPSHOT.jar"]
我可以使用任何脚本来更新DockerFile吗?或可以使用任何环境变量。
Can I use any script to update the DockerFile or can use any environment variable.
推荐答案
您可以在运行dokcer容器时为它分配一个静态IP地址,方法如下:步骤:
you can assign a static ip address to your dokcer container when you run it, following the steps:
1-创建自定义网络:
1 - create custom network:
docker network create --subnet=172.17.0.0/16 redis-net
2-运行redis容器以使用指定的网络,并分配ip地址:
2 - run the redis container to use the specified network, and assign the ip address:
docker run --net redis-net --ip 172.17.0.2 --name my-redis -d redis
到那时,您将拥有静态IP地址 172.17.0.2
用于 my-redis
容器,您无需检查它。
by then you have the static ip address 172.17.0.2
for my-redis
container, you don't need to inspect it anymore.
3-现在可以运行Java应用容器,但必须使用相同的网络:
3 - now it is possible to run the java appication container but it must use the same network:
docker run --net redis-net my-java-app
当然您可以使用env变量或任何方便设置的方法来优化解决方案。
of course you can optimize the solution, by using env variables or whatever you find convenient to your setup.
更多信息可在官方文档中找到(搜索-ip
):
More infos can be found in the official docs (search for --ip
):
- docker run
- docker network
编辑(添加docker-compose):
我刚刚发现也可以使用docker-compose分配静态ip,并且此答案给出了
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:
version: '3'
services:
redis:
container_name: redis
image: redis:latest
restart: always
networks:
vpcbr:
ipv4_address: 172.17.0.2
java-app:
container_name: java-app
build: <path to Dockerfile>
networks:
vpcbr:
ipv4_address: 172.17.0.3
depends_on:
- redis
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 172.17.0.0/16
gateway: 172.17.0.1
官方文档: https: //docs.docker.com/compose/networking/
希望这可以帮助您找到自己的出路。
hope this helps you find your way.
这篇关于在Dockerfile中动态添加Docker容器ip(redis)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!