Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMD in dockerfile vs command in docker-compose.yml

What is the difference?

Which is preferred?

Should CMD be omitted if command is defined?

like image 607
Yusif Avatar asked Dec 01 '25 12:12

Yusif


1 Answers

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
like image 161
David Maze Avatar answered Dec 04 '25 08:12

David Maze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!