简体   繁体   中英

Docker linking db container with spring boot and get environment variables

I have an springboot application container and mongodb container in docker.

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

So I'm running mongodb container first and after springboot container.

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

After that I want to get that environment variables in my 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.

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. But my app couldn't connect to mongodb container. Is there a way any good practise for this situation , also i tried to implement AbstractMongoConfiguration get systemEnvironment variables with @Value annotation.

My advise is to discard the IP inside the environment variables and properties at all.

--link myMongo:mongodb

Links myMongo container to host 'mongodb'. This manages docker inside your host config.

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.

If you want to know the IP and port on which your MongoDB is running, you can use the inspect command:

docker inspect myMongo

You'll get the IP and the port, which you can use directly without using --link command.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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