Beginner
Beginner

Reputation: 9095

switching command based on node env variable for the docker-compose.yml file

I am trying to host an application, so I have created a server and a client folder. In server folder node js and client its react using create-react-app.

So for docker, I have created two Dockerfile in server and client folder. In the project root created a docker-compose.yml file.

for local development, I need to have the auto reloading capability for the server so, I have put

command: nodemon index.js

in the docker-compose.yml file. Everything is working fine. when i build the docker. But when I host this application I need to change to

`command: node index.js`

The only way I think it will add a node environment variable when I host the application, but the problem is I can access in the index.js of server folder like

process.env.APPLICATION_ENVIRONMENT

but how can I access in the docker-compose.yml file? Since I want to use the same docker-compose.yml file for hosting and make developer to start work easily by having the capability of server auto reloading.

Is there any other better way to do this. ?

Upvotes: 1

Views: 317

Answers (1)

Jack Gore
Jack Gore

Reputation: 4242

docker-compose files support variable substitution. You can then use this to store and set the command you want to run directly in the docker-compose file.

E.g a sample docker-compose.yml:

version: "3"
services:
  server:
    build: ./server
    command: ${NODE_COMMAND:-nodemon} index.js

${NODE_COMMAND:-nodemon} will default to nodemon if no NODE_COMMAND variable is present in your shell. You can override this value in production by providing a value for NODE_COMMAND when you start the containers i.e :

$ NODE_COMMAND=node docker-compose up -d

Alternatively, on your hosted server you could create a .env file in the same directory that you run your docker-compose commands like so:

NODE_COMMAND=node

And docker-compose will automatically substitute the value in your compose file. See the linked page about variable substitution for more details.

Hopefully this helps.

Upvotes: 1

Related Questions