Docker bind db container to spring boot and get environment variables
I have a springboot app container and a mongodb container in docker.
docker run -p 27017:27017 -d --name myMongo mongo
So, I start the mongodb container first and after the springboot container.
docker run -p 8080:8080 --name mySpringApp --link myMongo:mongodb mySpringApp
After that, I want to get these environment variables in my springboot application.
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
Usually in the application.properties file I like this constant config for ip and port, so you can connect the mongodb container without any problem.
spring.data.mongodb.host=172.17.0.56
spring.data.mongodb.port=27017
But in this application.properties file i have a way to get environment variables, btw i tried #{systemEnvironment['MONGODB_PORT_5432_TCP_ADDR']}
like this notation. But my app couldn't connect to the mongodb container. Is there any good practice for this situation, also I tried to implement AbstractMongoConfiguration
get annotated systemEnvironment variables @Value
.
source to share
My advice would be to discard IP addresses inside environment variables and properties.
--link myMongo:mongodb
Binds container myMongo to host 'mongodb'. This manages docker inside your host config.
Now set up your properties like this:
spring.data.mongodb.host=mongodb
spring.data.mongodb.port=27017
Now there is no need to manage IP addresses inside the container.
source to share
If you want to find out the IP address and port that MongoDB is running on, you can use the check command:
docker inspect myMongo
You will get an IP address and port that you can use directly without using the -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
source to share