MongoNetworkError: failed to connect to server [mongodb:27017] on first connect

I just had a look at your project in Gitlab. The connection string inside your code is set up for a mongodb hostname of mongodb, which should work fine when you run both, the node process and the mongodb inside docker. In your question, you seem to be executing node from your host machine. This does not allow resolving the docker internal hostname. To check this, temporarily use localhost instead of mongodb as the hostname (using this connection string mongodb://admin:[email protected]). This will use the your host machine as target of the connection which works because you also mapped the ports in your docker-compose file that opens up the port on your host machine.

For your code to work in both scenarios (development on host and all-in-docker for prod), you can’t hardcode the connection string inside the code but rather need to make it configurable. One way is using environment variables for that. See the 12factor topic on configuration for conceptual details. This is especially important when it comes to credentials, which should never end up in a git repository at all. So, one common practice is to read such configuration from the environment. With node this is as simple as reading process.env.YOUR_VAR_FOR_MONGO_HOSTNAME. Check the node docs for details. This variable then needs to be exported or passed to the invocation of node. One tool that provides some convenience here is package for that is dotenv that basically allows specifying the env in a text file for development purposes. In your all-in-docker setup, you can then specify the environment variable accordingly back to mongodb instead of localhost.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top