Home > Enterprise >  dockerFile CMD on conditional
dockerFile CMD on conditional

Time:09-02

I have two containers a Flask and a Celery container. Both containers use similar configs except the CMD. How can I change the CMD to change based on an env variable?

if [ $CONTAINER = 'flask' ] ; then \
CMD \["uwsgi", "--ini", "uwsgi.ini"\] ; else \
CMD \["celery", "--app=flask_project.celery_app.celery", "worker"\]; \
fi

CodePudding user response:

Instead of having two separate CMDs, have one CMD that can run either thing.

In shell syntax, this might look like:

if [ "$CONTAINER" = flask ]; then
  exec wsgi --init uwsgi.ini "$@"
else
  exec celery --app=flask_project.celery_app.celery worker "$@"
fi

...in a Dockerfile, this might look like:

CMD [ "/bin/sh", "-c", "if [ \"$CONTAINER\" = flask ]; then exec uwsgi --ini uwsgi.ini \"$@\"; else exec celery --app=flask_project.celery_app.celery worker \"$@\"; fi" ]

The exec forces the copy of /bin/sh to replace itself in-place with wsgi or celery, so it doesn't exist in the process tree except for the short period it needs to make a decision.

CodePudding user response:

Instead of having two separate CMDs, have the CMD do the most common thing, and override the CMD if you need to do the other thing.

For example, you might say that the "most common" thing your container will do is to launch the Flask server

CMD ["uwsgi", "--ini", "uwsgi.ini"]

and if you just run the container it will do that

docker run -d --name web --net my-net -p 5000:5000 my-image

but you can also provide an alternate command after the docker run image name, and this will replace the Dockerfile CMD.

docker run -d --name celery --net my-net my-image \
  celery --app=flask_project.celery_app.celery worker

If you're in a Docker Compose setup, you can use the command: setting to specify this override, like

version: '3.8'
services:
  redis:
    image: redis
  web:
    build: .
    ports: ['5000:5000']
    depends_on: [redis]
  celery:
    build: .
    command: celery --app=flask_project.celery_app.celery worker
    depends_on: [redis]
  • Related