简体   繁体   中英

CMD in dockerfile vs command in docker-compose.yml

What is the difference?

Which is preferred?

Should CMD be omitted if command is defined?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM