Connecting to a local Mongodb Docker container from a local server with the spirit of Microservice

160 Views Asked by At

I composed a Mongodb service with Docker on my local machine, and the hostname is configured in docker-compose.yml with syntax container_name: mongodb, then with the spirit of Microservice I started a RESTful API service on a lightweight embedded server, say Jetty, also locally.

The problem is that the local RESTful API service cannot communicate with the Mongodb service by using the defined Mongodb container name - mongodb - on a local Docker container due to different network.

Questions:

  1. Is this a good practice, say by starting the RESTful API service just on an embedded server, esp. in production, without another Docker container differing from the Mongodb container?
  2. If this is a good practice, how to configure to make the RESTful API on the local embedded server have access to the Mongodb on a local Docker container?
1

There are 1 best solutions below

4
On

About running databases in Docker - this is totally nice. You probably would like to mount volumes from your host to configure database to store data there, as soon as storing data in container is not always convenient. Configuration is normally done by environment variable, passed to docker and config files, located in shared volumes.

Network itself should not be an issue, there are different network modes, supported by Docker, which allow you to communicate from host. The simplest, but not recommended for production purposes is just using --network=host. This prevents Docker from creating new networks and container shares your localhost. That means you are able to access all services from container just using localhost as a hostname.

Why not recommended: because this eliminates the level of protection/isolation, normally granted by Docker as soon as all you localhost networking becomes available in container.