Docker: Using CMD, RUN and ENTRYPOINT in a Dockerfile

2024-09-21

RUN

  • Purpose: Executes commands during the image build process.

  • When it runs: At build time, each RUN instruction creates a new layer in the image.

  • Why you’d use it:

    • To install software or dependencies.
    • To set up the file system or configuration.
    • To perform any actions needed to prepare the environment for your application.
  • Example:

    FROM ubuntu:latest
    RUN apt-get update && apt-get install -y python3

CMD

  • Purpose: Specifies the default command to run when a container starts.

  • When it runs: At runtime, when you start a container from the image.

  • Why you’d use it:

    • To define the main process of your container.
    • To provide sensible defaults that can be easily overridden.
  • Example:

    FROM python:3.9-slim-buster
    COPY app.py /app/
    CMD ["python3", "/app/app.py"]

ENTRYPOINT

  • Purpose: Configures the container to run as an executable.

  • When it runs: At runtime, when you start a container from the image.

  • Why you’d use it:

    • To create a container that behaves like a standalone command.
    • To provide a fixed base command with arguments that can be appended at runtime.
  • Example:

    FROM node:18-alpine
    COPY server.js /app/
    ENTRYPOINT ["node", "/app/server.js"]

Key Distinctions:

  • Overriding:

    • CMD can be easily overridden by providing a different command when running the container (docker run <image> <new_command>).
    • ENTRYPOINT cannot be directly overridden; arguments passed to docker run are appended to the ENTRYPOINT command.
  • Common Use Cases:

    • RUN: Primarily for setting up the image during the build process.
    • CMD: Suitable for defining the default behavior of the container, especially when you expect users to sometimes want to run a different command.
    • ENTRYPOINT: Ideal when you want your container to act as a single executable, where the main command is fixed, but you allow for additional arguments.

Feel free to ask if you have any more specific questions or want to explore scenarios where you’d combine these instructions!