skip to Main Content

What is the difference?

Which is preferred?

Should CMD be omitted if command is defined?

2

Answers


  1. command overrides the CMD in dockerfile.
    If you control the dockerfile yourself, put it there. It is the cleanest way.

    If you want to test something or need to alter the CMD while developing it is faster than always changing the dockerfile and rebuild the image.

    Or if it is a prebuilt image and you don’t want to build a derivate FROM ... image just to change the CMD it is also a quick solution doing it by command.

    Login or Signup to reply.
  2. In the common case, you should have a Dockerfile CMD and not a Compose command:.

    command: in the Compose file overrides CMD in the Dockerfile. There are some minor syntactic differences (notably, Compose will never automatically insert a sh -c shell wrapper for you) but they control the same thing in the container metadata.

    However, remember that there are other ways to run a container besides Compose. docker run won’t read your docker-compose.yml file and so won’t see that command: line; it’s also not read in tools like Kubernetes. If you build the CMD into the image, it will be honored in all of these places.

    The place where you do need a command: override is if you need to launch a non-default main process for a container.

    Imagine you’re building a Python application. You might have a main Django application and a Celery worker, but these have basically the same source code. So for this setup you might make the image’s CMD launch the Django server, and override command: to run a Celery worker off the same image.

    # Dockerfile
    # ENTRYPOINT is not required
    CMD ["./manage.py", "runserver", "0.0.0.0:8080"]
    
    # docker-compose.yml
    version: '3.8'
    services:
      web:
        build: .
        ports: ['8080:8080']
        # no command:
      worker:
        build: .
        command: celery worker
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search