Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally detecting whether a Node server is running inside a Docker Container

I have my node.js code where I establish mongodb connections like this: mongodb://localhost:27017/mycollection

Now, I put my server in one container and db in another container and I am able to connect to my db from the server like this: mongodb://mycontainer:27017/mycollection

I have this connection string configured in my server code/config.

Now, how do I detect whether a person is running the server in a container or not and accordingly take the connection string for the db?

If he is running it in the host machine, I want to use the first connection string with localhost and connect to the db in the host machine and if he connects through a container, I want to use the container link name to connect as mentioned in the second case.

Is there any way to do this?

like image 910
Vignesh T.V. Avatar asked Jun 01 '18 09:06

Vignesh T.V.


1 Answers

Personally, when I want to accomplish that, I set an ENV variable in the Dockerfile like the following:

ENV DATABASE_HOST db

You can have the full documentation on the Dockerfile reference.

Then, in your Node.js code source, you need to know whether the DATABASE_HOST is set or not (I can redirect you to this Stack Overflow Jayesh's post: Read environment variables in Node.js):

var dbHost = 'localhost';

if (process.env.DATABASE_HOST) {
    dbHost = process.env.DATABASE_HOST;
}

or in one line:

var dbHost = process.env.DATABASE_HOST || 'localhost';

Then, for MongoDB connection:

var mongodbConnection = 'mongodb://' + dbHost + ':27017/mycollection'

Now, when you run the container, you must link the container in the docker run command with --link <your mongodb container>:db (since db is the value set in the ENV variable).

But, you can also use the option -e DATABASE_HOST=<somthing else> (again with the docker run command) and use a MongoDB container under another name: -e DATABASE_HOST=anotherOne --link mongo:anotherOne.

And again, you can use an external MongoDB without linking any container if you want (which is not in another container maybe): -e DATABASE_HOST=www.mymongo.com.

EDIT: This solution is maybe better than just identifying if the application is run in a Docker container because with this one your code is usable anywhere.

like image 72
Paul Rey Avatar answered Sep 27 '22 21:09

Paul Rey