ar099968
ar099968

Reputation: 7537

Docker different CMD based on ENV

I want run a different command in the same image, based on an ENV variable, eg.:

FROM node:12-slim

ENV MODE server
# ENV MODE worker

# workdir
RUN mkdir -p /opt/backend
WORKDIR /opt/backend
COPY . /opt/backend

# Install node modules
RUN npm install --production --no-audit

EXPOSE 3000


RUN if [ "server" = "$MODE" ] ; then \
    CMD [ "node", "./build/server.js"]; \
  else \
    CMD [ "node", "./build/worker.js"]; \
fi

This example didn't works, how fix it?

Upvotes: 0

Views: 165

Answers (3)

David Maze
David Maze

Reputation: 158908

When you launch the container, you can specify the command, and that will override the CMD in the Dockerfile.

For example, let's say you think the container is "usually" the server, so you write

EXPOSE 3000
CMD ["node", "./build/server.js"]

Now you can build and run that container, but run a second container with a different command.

docker build -t my-node-app .
docker run -d --name server \
  -p 3000:3000
  my-node-app
  # with its default command
docker run -d --name worker \
  my-node-app \
  node ./build/worker.js

You can do something similar specifying a command: in a docker-compose.yml file.

Upvotes: 2

Matthias Reissner
Matthias Reissner

Reputation: 355

Just create a shell script inside your container which contains your

if ….
    ….. \
  else \
    …..  \
fi

and run it

Upvotes: 0

Adiii
Adiii

Reputation: 59946

You can do this in entry point instead of CMD.

#!/bin/sh

if [ "server" = "${MODE} ]; then
  # check the correct path
  echo "application starting with server mode"
  node ./build/server.js
else 
  node ./build/worker.js 
fi

Dockerfile will look like

FROM node:12-slim

ENV MODE server
RUN mkdir -p /opt/backend
WORKDIR /opt/backend
COPY . /opt/backend
# Install node modules
RUN npm install --production --no-audit
EXPOSE 3000
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
entrypoint ["/entrypoint.sh"]

Upvotes: 2

Related Questions