DOCKER · DOCKER FROM SCRATCH · CHAPTER 2

Docker Commands

Create, list, stop, remove and step into containers: the commands you will use every day.

7 min readCourse: Docker from ScratchLevel: beginner

From point A to point B

Point A: you know what a container is and you have Docker installed, but every command still sends you to Google. Point B: by the end of this chapter you will create, list, stop, restart and remove containers and images with ease, and you will step into a running container without stopping it.

These are the commands you will use every day. Practise them in your terminal as you read: it is the fastest way to make them stick.

docker run: create and start in one step

docker run creates a container from an image and starts it. If the image is not on your machine, Docker downloads it first from the registry (Docker Hub by default). The first time takes a little longer; after that, the image is already local.

docker run nginx            # downloads nginx if needed and starts it
docker pull centos          # only downloads the image, no container
docker run centos           # creates a centos container... that ends instantly

Why does the centos container end right away? Because of the golden rule from the previous chapter: a container lives as long as its main process. The centos image starts bash with no terminal, bash exits and so does the container. Give it a process that lasts:

docker run centos sleep 20  # lives for 20 seconds, then stops

Tags: which version you run

After the colon comes the image tag. If you do not set one, Docker uses latest. In a lab it does not matter; in production, always pin the version.

docker run ubuntu           # same as ubuntu:latest
docker run ubuntu:22.04     # a specific version

docker ps: what is running and what is not

docker ps          # running containers only
docker ps -a       # all of them, stopped ones included

Each row shows the ID (first 12 characters), the image, the command, the status and a name. If you do not name it, Docker makes one up from two random words, such as silly_hopper. To refer to a container you can use its name, its full ID or just the first characters of the ID, as long as they are unique.

docker run -d --name web nginx:alpine   # you choose the name
docker ps

The status tells the story: Up 3 minutes means it is running; Exited (0), that it ended cleanly; any other code means it ended because of an error or a signal.

Container states and the commands that move between them docker run creates and starts a container. A running container goes to Exited with docker stop or when its main process ends, and docker start brings it back. docker rm removes an exited container. docker ps lists running containers; docker ps -a lists all of them. LIFECYCLE OF A CONTAINER Imagenginx:alpine RunningUp 2 minutes ExitedExited (0) · (137) Removed docker run docker stop or the process ends docker start docker rm docker psonly Running docker ps -aRunning + Exited

Each command moves the container from one state to another. Diagram: The House of Routing.

Stop, restart and remove

docker stop web    # stops the container
docker start web   # starts it again, with the same configuration
docker rm web      # removes it (it must be stopped)
docker rm -f web   # stops and removes it in one step

What docker stop does under the hood

docker stop sends the SIGTERM signal to the main process so it can shut down cleanly. If it is still alive after 10 seconds, Docker forces it with SIGKILL.

That is why you sometimes see Exited (137) in docker ps -a: 137 is 128 + 9, and 9 is the number of SIGKILL. It means the process ignored SIGTERM and Docker had to force it. It happens a lot with processes like sleep, which do not shut themselves down when they run as PID 1.

Quick clean-up. docker container prune removes all stopped containers at once. It asks for confirmation: read it before you accept.

Managing images

docker images                 # images on your machine, with their size
docker pull jesusespinoza/my-web   # a user's image: user/repository
docker rmi nginx              # removes an image
docker image rm nginx         # the same, with the newer syntax

If you try to remove an image that a container uses, even a stopped one, Docker refuses. Remove those containers first with docker rm, then the image.

Two syntaxes, one result. Docker grouped its commands by object: docker container ... and docker image .... The short commands still work: docker rm equals docker container rm, and docker rmi equals docker image rm.

Run a command and exit

You can use a container to run a single task. For example, check which Ubuntu version an image ships:

docker run ubuntu:22.04 cat /etc/os-release

The container starts, runs cat, prints the result and ends. You will see it as Exited (0) in docker ps -a. If you will not need it again, add --rm and Docker removes it as soon as it finishes:

docker run --rm ubuntu:22.04 cat /etc/os-release

Foreground and background

By default, docker run works in the foreground (attached): you see the container's output and your terminal is busy until it ends. With -d (detached) you send it to the background: Docker returns the ID and you get your terminal back.

Attached vs detached containers Without -d the container runs in the foreground and holds your terminal. With -d it runs in the background and returns its ID. docker attach connects your terminal again, and CTRL-p CTRL-q detaches without stopping the container when it was started with -it. ATTACHED (FOREGROUND) DETACHED (BACKGROUND) $ docker run timer Your terminal shows its output you cannot type other commands until it ends or you press CTRL-c $ docker run -d timer a1b2c3d4e5f6… Runs in background docker attach a1b2 CTRL-p CTRL-q to detach again (container started with -it)

With -d the container keeps running and so do you. Diagram: The House of Routing.

docker run -d ubuntu sleep 1500   # in the background
docker ps                         # there it is, Up
docker attach <id>                # connects your terminal to its output

To let go without stopping it, press CTRL-p followed by CTRL-q. It works if the container was started with -i and -t. If you press CTRL-c instead, you usually stop the main process and, with it, the container.

Interactive mode and docker exec

Step into a new container: -it

-i keeps standard input open and -t allocates a terminal. Together they put you inside the container, as if it were another machine:

docker run -it ubuntu bash
# you are inside: try ls, cat /etc/os-release, ps
exit                             # leave bash and the container stops

Step into a container that is already running: docker exec

docker exec starts an extra process inside a running container. It does not restart it or touch its main process.

docker exec runs an extra process inside a running container The container keeps its main process, PID 1. docker exec starts a second process inside the same container, sharing its filesystem and network. When that process ends, the container keeps running. DOCKER EXEC · ONE MORE PROCESS, SAME CONTAINER container: mylinux (Up) PID 1 · sleep 100main process cat /etc/hostsextra process same filesystem · same network · same namespaces docker execfrom your terminal when the extra process ends, the container keeps running

exec adds a process to the container; when it ends, the container stays as it was. Diagram: The House of Routing.

docker run --name mylinux -d ubuntu sleep 100
docker exec mylinux cat /etc/hosts      # runs and returns
docker exec -it mylinux bash            # opens a terminal inside
exit                                    # you leave, and mylinux stays Up
Key difference. If you leave a docker run -it ... bash, the container stops because bash was its main process. If you leave a docker exec -it ... bash, the container keeps running because bash was an extra process.

Lab: Jenkins on your machine

Put it all together with a real application. Jenkins, the automation server, runs on the container's port 8080 and stores its data in /var/jenkins_home.

mkdir -p $HOME/jenkins-data
docker run -d --name app01 \
  -p 4545:8080 \
  -v $HOME/jenkins-data:/var/jenkins_home \
  jenkins/jenkins:lts

docker ps                           # app01 is Up
docker logs app01                   # the initial password appears here

Open http://localhost:4545 in your browser. Two options do the magic, and you will explore them in depth in the next chapter:

  • -p 4545:8080 publishes the container's port 8080 on your machine's port 4545.
  • -v mounts a folder from your machine inside the container. If you remove app01 and create another one with the same folder, Jenkins keeps its configuration.
If Jenkins does not start on Linux, check the folder permissions: the Jenkins container runs as an unprivileged user (UID 1000), which needs to be able to write to it.

Command cheat sheet

CommandWhat it is for
docker run IMAGECreates and starts a container; downloads the image if needed
docker run -d / --name / --rmBackground / your own name / remove when it ends
docker run -it IMAGE bashInteractive terminal in a new container
docker ps / docker ps -aRunning containers / all of them
docker stop / docker startStop (SIGTERM, then SIGKILL) / start again
docker rm / docker rm -fRemove a stopped container / stop and remove
docker images / docker pullList local images / download an image
docker rmi or docker image rmRemove an image no container uses
docker attach · CTRL-p CTRL-qConnect to a background container · let go without stopping it
docker exec [-it]Run an extra process in a running container
docker logsSee a container's output

Challenge

Answer before you open the solution. Getting it wrong here is the cheapest way to learn.

1. You run docker run centos and it does not show up in docker ps. What happened?

The container ended. Its main process, bash, started without a terminal and exited. You will see it in docker ps -a as Exited.

2. After docker stop, a container shows Exited (137). What does that number tell you?

That Docker had to force it with SIGKILL (128 + 9) because the process did not shut down on SIGTERM within 10 seconds.

3. docker rmi nginx fails even though no container is running. Why?

A stopped container uses that image. Remove it with docker rm and try again.

4. You need to check a file inside a production container without restarting it. Which command do you use?

docker exec. It starts an extra process inside the running container without touching its main process.

What you take away

  • docker run = download if needed + create + start.
  • docker ps shows what is running; docker ps -a also shows what has stopped.
  • docker stop asks with SIGTERM and, after 10 seconds, forces with SIGKILL: hence the 137.
  • You cannot remove an image that a container uses, even a stopped one.
  • -d gives your terminal back; CTRL-p CTRL-q lets go without stopping.
  • exec steps into a running container without restarting it.

In the next chapter we dig deeper into docker run: ports, volumes, environment variables and inspecting containers.

Official resources

Source and credits. Chapter written from Jesús Espinoza's study notes on KodeKloud's Docker for Absolute Beginners course (December 2024). Text drafted with AI assistance; original diagrams by The House of Routing. Technical details were checked against the official Docker documentation.

Navigate