Choosing a start command for your Docker image

Introduzione a Docker

Tim Sangster

Software Engineer @ DataCamp

What is a start command?

The hello-world image prints text and then stops.

docker run hello-world
Hello from Docker!

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon created a new container from the hello-world image which runs the
    executable that produces the output you are currently reading.
 3. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.
Introduzione a Docker

What is a start command?

An image with python could start python on startup.

docker run python3-sandbox
Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
...
....
>>> exit()
repl@host:/#
Introduzione a Docker

Running a shell command at startup

CMD <shell-command>

The CMD instruction:

  • Runs when the image is started.
  • Does not increase the size of the image .
  • Does not add any time to the build.
  • If multiple exist, only the last will have an effect.
Introduzione a Docker

Typical usage

Starting an application to run a workflow or that accepts outside connections.

CMD python3 my_pipeline.py
CMD postgres

Starting a script that, in turn, starts multiple applications

CMD start.sh
CMD python3 start_pipeline.py
Introduzione a Docker

When will it stop?

$$

  • hello-world image -> After printing text
  • A database image -> When the database exits

$$

A more general image needs a more general start command.

  • An Ubuntu image -> When the shell is closed
Introduzione a Docker

Overriding the default start command

Starting an image

docker run <image>

Starting an image with a custom start command

docker run <image> <shell-command>

Starting an image interactively with a custom start command

docker run -it <image> <shell-command>
docker run -it ubuntu bash
Introduzione a Docker

Summary

Usage Dockerfile Instruction
Add a shell command run when a container is started from the image. CMD <shell-command>

Usage Shell Command
Override the CMD set in the image docker run <image> <shell-command>
Override the CMD set in the image and run interactively docker run -it <image> <shell-command>
Introduzione a Docker

Let's practice!

Introduzione a Docker

Preparing Video For Download...