Sobes.tech
Middle

What are CMD and ENTRYPOINT used for in Docker?

sobes.tech AI

Answer from AI

CMD and ENTRYPOINT define which command the container will execute upon startup.

  • CMD (Command): Specifies the default command that will be executed when the container starts if no command is provided in the docker run call. It can contain only an executable or an executable with arguments. It can be overridden by arguments in the docker run command.

    # CMD in exec form
    CMD ["nginx", "-g", "daemon off;"] 
    # CMD in shell form (not recommended for production due to signal handling issues)
    # CMD nginx -g "daemon off;" 
    
  • ENTRYPOINT: Defines the command that will always be executed when the container starts. Arguments provided in the docker run command will be passed to this command as parameters. Often used together with CMD to specify a part of the command (ENTRYPOINT) and its default arguments (CMD).

    # ENTRYPOINT in exec form
    ENTRYPOINT ["/usr/local/bin/my-script.sh"]
    

Comparison of CMD and ENTRYPOINT:

Characteristic CMD ENTRYPOINT
Purpose Default command Main command that always executes
Ability to override via docker run Yes (by argument) No (only via --entrypoint flag)
Usage with docker run arguments Arguments replace CMD Arguments are added to ENTRYPOINT
Recommended usage Setting arguments for the executable Setting the executable that runs