Dockerfile: Understanding the Difference between ADD vs COPY and ENTRYPOINT vs CMD

Dockerfile instructions play a vital role in defining the behavior and characteristics of your Docker containers. Two sets of instructions often cause confusion for beginners: ADD vs COPY and ENTRYPOINT vs CMD. Let’s demystify these differences to ensure a clear understanding of their roles and use cases.

ADD vs COPY:

ADD:

  • Functionality:
  • In addition to copying files, ADD allows remote URLs, local tar files, and automatically decompresses compressed files.
  • Use Case:
  • Preferably used when dealing with compressed files or remote resources.
ADD https://example.com/file.tar.gz /app/

COPY:

  • Functionality:
  • Primarily used for copying local files and directories from the build context to the image.
  • Use Case:
  • Recommended for standard file and directory copying needs.
COPY ./source /app/

Best Practice:

  • Generally, use COPY for most cases, as it’s more transparent and predictable. Reserve ADD for specific use cases like handling compressed files.

ENTRYPOINT vs CMD:

ENTRYPOINT:

  • Functionality:
  • Defines the default executable for the container. Additional command-line arguments can be appended when running the container.
  • Use Case:
  • Suitable for defining the primary process that should run in the container.
ENTRYPOINT ["nginx", "-g", "daemon off;"]

CMD:

  • Functionality:
  • Specifies default parameters for the ENTRYPOINT. CMD can be overridden by providing additional command-line arguments during container runtime.
  • Use Case:
  • Ideal for providing default settings or arguments for the primary process defined by ENTRYPOINT.
CMD ["nginx", "-g", "daemon off;"]

Best Practice:

  • Combine ENTRYPOINT and CMD to provide default parameters for the primary process. Use CMD to define default settings that are likely to be overridden.

Example:

ENTRYPOINT ["nginx", "-g"]
CMD ["daemon off;"]

Note:

  • CMD is often used without ENTRYPOINT, providing a default command for the container.

Conclusion:

Understanding the distinctions between ADD and COPY, as well as ENTRYPOINT and CMD, is crucial for building effective Dockerfiles. Choose the instruction that best aligns with your specific use case, whether it involves copying files or defining container behavior.

May your Dockerfiles be clear, concise, and tailored to meet the needs of your containerized applications. Happy Dockerizing!