-
Notifications
You must be signed in to change notification settings - Fork 3
Docker
You have multiple ways of running your NodeJS applications. One which is to create a container which has all the required data mounted and is linked to mongo container.
Run the following command from project directory.
docker run -it --name node -v "$(pwd)":/data --link mongo:mongo -w /data -p 3000:3000 node bash
> node server.js
or
docker run -it --name automation -v "$(pwd)":/data --link mongo:mongo -w /data -p 3000:3000 node node server.js
If you’re running these examples with MongoDB course examples it will fail. This is because it’s trying to connect to Mongo database on localhost, but our Mongo database isn’t on local machine. There are multiple ways to fix this:
- hard code the connection string (with linked container IP);
- use environment variables which are added automatically by Docker (when linking);
- use hosts entry which is added automatically by Docker (when linking).
Example below contains the representation of all those methods. Please choose the one which you like most or is best for your use case.
// Original connect
MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) {
// ...
});
// Connect using environment variables
MongoClient.connect('mongodb://'+process.env.MONGO_PORT_27017_TCP_ADDR+':'+process.env.MONGO_PORT_27017_TCP_PORT+'/blog', function(err, db) {
// ...
});
// Connect using hosts entry
MongoClient.connect('mongodb://mongo:27017/blog', function(err, db) {
// ...
});
After fixing the connect() method the application should run successfully. You can reach it by opening http://localhost:3000 (if it was IP address of your Docker application) or if you added the Docker IP as docker in your hosts file http://docker:3000.