docker-compose NodeJS + Mongodb with mongoose, dynamically get the mongo container ip
Check out Networking section in Docker Compose Manual. Especially this interesting paragraph:
Each container can now look up the hostname web or db and get back the appropriate container’s IP address. For example, web’s application code could connect to the URL postgres://db:5432 and start using the Postgres database.
So given your example, you can freely change line
mongoose.connect('mongodb://172.19.0.2/test');
to line
mongoose.connect('mongodb://mongo/test');