Search⌘ K
AI Features

Docker Kata 2: Disconnected Containers

Explore how to run Docker containers in the background using detached mode, execute commands within running containers, and manage container logs and network settings. This lesson helps you understand container lifecycle, interaction, and monitoring to effectively manage Docker environments.

The first kata demonstrated containers that exit immediately after they’re run. This kata will teach us how to run a container that continues running in the background after executing the docker container run command.

Step 1: Run a disconnected container

The command to run a disconnected container in the background is given below.

Shell
docker container run -d ubuntu /bin/sh -c "while true; do echo hello docker; sleep 1; done"

The output will be something like this:

Commands

Parameter

Description

docker container

This is the parent command.

run

This is the command that runs a container from an image.

-d

The -d parameter runs a disconnected container.

ubuntu

This is the name of the image to run; in this case, the Ubuntu Linux image.

/bin/sh

This is the command to run inside the container when it starts. This is the shell, which can run commands and scripts.

-c

The -c parameter indicates that the next parameter will be the script to run; without the -c parameter, the shell will expect a file name parameter.


"while true; do echo hello docker; sleep 1; done"

This is the script to be run by the shell:

  • while true;: This causes the script to run forever (true is always true!).
  • do echo hello docker;: This echoes the text “hello docker” to the console.
  • sleep 1;: This echoes the text “hello docker” to the console.
  • done: This ends the script.

This step demonstrates how Docker can run a disconnected container in the background. Running a disconnected container is essentially the opposite of running it interactively. A disconnected container will run without user input or interaction as long as its start process runs.

This command does the following:

  • Runs a disconnected Ubuntu container
  • Specifies the command to run after the image name
  • Uses /bin/sh to run the sh shell, which runs scripts in the bash command language
  • Executes the inline script: "while true; do echo hello docker; sleep 1; done"

When this command is run, there’s one output, which is the ID of the started container. The Unix shell program bin/sh acts as the start command. The inline ...