简体   繁体   English

Docker将db容器与spring boot连接起来并获取环境变量

[英]Docker linking db container with spring boot and get environment variables

I have an springboot application container and mongodb container in docker. 我在docker中有一个springboot应用程序容器和mongodb容器。

docker run -p 27017:27017 -d --name myMongo mongo

So I'm running mongodb container first and after springboot container. 所以我首先运行mongodb容器,然后运行springboot容器。

docker run -p 8080:8080 --name mySpringApp --link myMongo:mongodb mySpringApp

After that I want to get that environment variables in my springboot app. 之后我想在springboot app中获取环境变量。

MONGODB_PORT=tcp://172.17.0.5:27017
MONGODB_PORT_5432_TCP=tcp://172.17.0.5:27017
MONGODB_PORT_5432_TCP_PROTO=tcp
MONGODB_PORT_5432_TCP_PORT=27017
MONGODB_PORT_5432_TCP_ADDR=172.17.0.5

In application.properties file normally I have like that constant configuration for ip and port, so it connect mongodb container without any problem. 在application.properties文件中,我通常喜欢ip和port的常量配置,所以它连接mongodb容器没有任何问题。

spring.data.mongodb.host=172.17.0.56
spring.data.mongodb.port=27017

But in that application.properties file i there a way to get that environment variables , btw i tried #{systemEnvironment['MONGODB_PORT_5432_TCP_ADDR']} like this notation. 但是在那个application.properties文件中我有办法获取环境变量,顺便说一句,我尝试了#{systemEnvironment['MONGODB_PORT_5432_TCP_ADDR']}这样的表示法。 But my app couldn't connect to mongodb container. 但我的应用程序无法连接到mongodb容器。 Is there a way any good practise for this situation , also i tried to implement AbstractMongoConfiguration get systemEnvironment variables with @Value annotation. 有没有办法对这种情况有任何好的做法,我也试图用@Value注释实现AbstractMongoConfiguration获取@Value变量。

My advise is to discard the IP inside the environment variables and properties at all. 我的建议是根据环境变量和属性丢弃IP。

--link myMongo:mongodb

Links myMongo container to host 'mongodb'. 将myMongo容器链接到主机'mongodb'。 This manages docker inside your host config. 这可以管理主机配置中的docker。

Now adjust your properties as follows: 现在按如下方式调整属性:

spring.data.mongodb.host=mongodb
spring.data.mongodb.port=27017

Now there is no need to manage IPs inside the container. 现在无需管理容器内的IP。

If you want to know the IP and port on which your MongoDB is running, you can use the inspect command: 如果您想知道运行MongoDB的IP和端口,可以使用inspect命令:

docker inspect myMongo

You'll get the IP and the port, which you can use directly without using --link command. 您将获得IP和端口,您可以直接使用它而无需使用--link命令。

spring.data.mongodb.host=172.17.0.2 // for me mongo was running on this IP, check yours 
spring.data.mongodb.port=27017

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM