Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 111 ยท Getting Started

Your First Container

Run your first container with docker run, see what happens step by step, work interactively with -it, use --rm to clean up, and read exit codes and common errors.

docker run is the command you will type more often than any other. In one line it finds an image, downloads it if needed, creates a container from it, starts the container and connects your terminal to it. Understanding exactly what happens in that one line is the best foundation for everything else in Docker.

In this lesson you will run a one-off command in a container, watch the image being pulled, look at the stopped container left behind, work inside a container interactively, learn why --rm matters, and see what Docker reports when things go wrong. All you need is a working installation (see Installing Docker).

The shape of docker run

TEXT
docker run [OPTIONS] IMAGE [COMMAND] [ARGUMENTS...]
  • IMAGE is the template to start from, written as name:tag (for example alpine:3.22). If you leave out the tag, Docker uses latest.
  • COMMAND and ARGUMENTS replace the image's default command. If you leave them out, the image decides what runs.
  • OPTIONS change how the container is created. You will meet the important ones in this lesson and the next ones.

Here is the smallest useful example. It starts Alpine Linux, prints a sentence and exits:

CONSOLE
$ docker run alpine:3.22 echo "Hello from a container"
Unable to find image 'alpine:3.22' locally
3.22: Pulling from library/alpine
Digest: sha256:2e0b81d60597f449baa56dc25d355367869d2dca4cd57e866f1e2b52af3eb55f
Status: Downloaded newer image for alpine:3.22
Hello from a container

The first four lines come from Docker; the last line is the output of echo running inside the container. Run the same command again and Docker is silent about images, because the image is now stored on your machine:

CONSOLE
$ docker run alpine:3.22 echo "Hello from a container"
Hello from a container

What happens step by step

When you press Enter, Docker does the following:

TEXT
  docker run alpine:3.22 echo "Hello..."
        โ”‚
        โ–ผ
  1. CLI sends the request to the daemon
  2. Daemon looks for alpine:3.22 in the local image store
        โ”œโ”€โ”€ missing? โ”€โ”€โ–ถ 3. pull it from the registry (Docker Hub)
        โ–ผ
  4. Daemon creates a container: a new writable layer on top of the image,
     plus a name, an ID, a network and isolation settings
  5. Daemon starts it: the command "echo Hello..." becomes the container's
     main process (PID 1 inside the container)
  6. Output streams back to your terminal
  7. The process exits -> the container stops (it is NOT deleted)

Two ideas deserve emphasis.

A container lives exactly as long as its main process. There is no "idle" container. When echo finished, the container stopped. A web server container stays up only because the web server process keeps running.

A stopped container still exists. Docker keeps it (its file system changes, its logs and its exit status) so you can inspect it. Look at it with docker ps -a, where -a means "all, including stopped":

CONSOLE
$ docker ps -a
CONTAINER ID   IMAGE         COMMAND                  CREATED          STATUS                      PORTS     NAMES
a1b2c3d4e5f6   alpine:3.22   "echo 'Hello from a โ€ฆ"   12 seconds ago   Exited (0) 11 seconds ago             quirky_dewdney

(IDs, times and names will differ on your machine; with other containers present you will see more rows.) Read the columns from left to right: the short container ID, the image it was created from, the command it ran, when it was created, its status (Exited (0) means it finished with exit code 0, which means success) and an automatically generated name. Docker invents names from two random words when you do not give one. You choose your own with --name:

CONSOLE
$ docker run --name greeter alpine:3.22 echo hi
hi
$ docker ps -a --filter name=greeter --format 'table {{.Names}}\t{{.Image}}\t{{.Command}}\t{{.Status}}'
NAMES     IMAGE         COMMAND     STATUS
greeter   alpine:3.22   "echo hi"   Exited (0) 2 seconds ago

The --filter option narrows the list to matching containers, and --format with a Go template prints only the columns you want. You will use both constantly in Listing and Inspecting.

Remove a container you no longer need with docker rm, which prints the name it removed:

CONSOLE
$ docker rm greeter
greeter

Cleaning up automatically with --rm

If every docker run leaves a stopped container behind, your machine fills with clutter. For throwaway commands, add --rm and Docker deletes the container as soon as it exits:

CONSOLE
$ docker run --rm alpine:3.22 cat /etc/os-release
NAME="Alpine Linux"
ID=alpine
VERSION_ID=3.22.7
PRETTY_NAME="Alpine Linux v3.22"
HOME_URL="https://alpinelinux.org/"
BUG_REPORT_URL="https://gitlab.alpinelinux.org/alpine/aports/-/issues"

Afterwards docker ps -a shows no new container. A good habit: use --rm whenever you do not need the container's logs or files afterward. This tutorial uses it in most one-off examples.

The image is not deleted by --rm. Only the container is. Images stay on disk until you remove them with docker rmi, so the next run is fast.

Working inside a container: -i and -t

So far each container ran one command and left. To get a shell inside a container, you need two flags that are almost always used together:

  • -i (--interactive) keeps the container's standard input open, so what you type reaches the process.
  • -t (--tty) allocates a pseudo-terminal, so you get a prompt, line editing and colors.

Combined as -it, they give you a proper interactive session:

CONSOLE
$ docker run --rm -it alpine:3.22 sh
/ # whoami
root
/ # hostname
033bf9ad7811
/ # cat /etc/alpine-release
3.22.7
/ # ps
PID   USER     TIME  COMMAND
    1 root      0:00 sh
   11 root      0:00 ps
/ # touch /hello.txt
/ # ls /hello.txt
/hello.txt
/ # exit
$

Look closely at what this shows:

  • You are root, but root inside the container. It runs with a reduced set of Linux capabilities, so it is less powerful than root on the host. (See Non-Root Users and Capabilities.)
  • The hostname is the container's short ID, as you saw in docker ps.
  • ps shows only two processes: your shell as PID 1 and ps itself. The container has its own process list and cannot see the host's processes.
  • When you type exit, the shell ends, which is the container's main process, so the container stops. Because of --rm it is also deleted.

The file /hello.txt existed only in that container's writable layer. The next docker run starts from the clean image again, which is why containers are called disposable.

If you forget -t and -i, a shell will exit immediately because it reads end-of-file from an empty input. If you pass -t but your input is not a terminal (for example you pipe text into the command), Docker refuses:

CONSOLE
$ echo hi | docker run --rm -it alpine:3.22 sh
cannot attach stdin to a TTY-enabled container because stdin is not a terminal

For piped input use -i alone:

CONSOLE
$ echo "typed input" | docker run --rm -i alpine:3.22 sh -c 'echo "line: $(cat)"'
line: typed input

Your changes do not survive, but the container does

Containers keep their changes until they are removed. If you do not use --rm, you can come back to a stopped container and see them. This sequence shows docker diff, which lists what changed in a container compared with its image (A means added):

CONSOLE
$ echo 'touch /note.txt' | docker run --name notes -i alpine:3.22 sh
$ docker run --rm alpine:3.22 ls /note.txt
ls: /note.txt: No such file or directory
$ docker diff notes
A /note.txt
$ echo 'ls /note.txt' | docker start -ai notes
/note.txt
$ docker rm notes
notes

The file is invisible to a new container made from the same image, but visible when you restart the same container with docker start -ai (-a attaches output, -i keeps input open). This difference between "a new container" and "the same container again" is one of the most common sources of confusion for beginners. When in doubt, remember: docker run always creates a new container; docker start restarts an existing one.

Exit codes and errors

Every program ends with an exit code, and docker run passes it on, so the shell variable $? works as usual:

CONSOLE
$ docker run --rm alpine:3.22 sh -c 'exit 3'
$ echo $?
3

Docker itself uses a few special codes when it cannot even run your command:

Exit code Meaning Example
0 The command succeeded echo hi
125 The Docker daemon or docker run itself failed image not found, port already in use
126 The command was found but could not be executed running a file without execute permission
127 The command was not found in the image a typo such as nosuchcmd
137 Killed with SIGKILL (128 + 9), often an out-of-memory kill or docker kill

Here is what 127 looks like, caused by a program that does not exist in the image:

CONSOLE
$ docker run --rm alpine:3.22 nosuchcmd
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: exec: "nosuchcmd": executable file not found in $PATH

Run 'docker run --help' for more information
$ echo $?
127

And what happens when the image name is wrong, or you are not allowed to pull it:

CONSOLE
$ docker run --rm nosuchimage-demo:1
Unable to find image 'nosuchimage-demo:1' locally
docker: Error response from daemon: pull access denied for nosuchimage-demo, repository does not exist or may require 'docker login'

Run 'docker run --help' for more information

Docker's message mentions docker login because for a private repository, Docker Hub says the same thing as for a missing one, to avoid leaking which repositories exist. Check the spelling first.

Exit code 137 after a long run is often the kernel killing the container for using too much memory. If you see it unexpectedly, check Resource Limits and Debugging Containers.

Choosing a good first set of habits

Beginners benefit from a short list of rules that avoid most early trouble:

  1. Always pin a tag (alpine:3.22, not just alpine) so the result does not change under you. More on this in Understanding Images.
  2. Use --rm for experiments and one-off commands.
  3. Use --name for containers you will refer to again.
  4. Use -it only when you want to type into the container; leave it off for scripts and CI.
  5. Read the status with docker ps -a before assuming a container is running.

Next, you need a mental model of the machinery behind the command, so that the pieces make sense when we meet them again.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you run docker run alpine:3.22 echo hi and the image is not on your machine?

    docker run pulls missing images automatically, which is why you see the 'Unable to find image locally' lines the first time.
  2. 2. After docker run alpine:3.22 echo hi finishes, what is true?

    A container stops when its main process ends but is not removed unless you used --rm or run docker rm. Exited (0) means the command succeeded.
  3. 3. What do the flags -i and -t do in docker run -it alpine:3.22 sh?

    -i (--interactive) keeps standard input attached and -t (--tty) gives you a terminal with a prompt. Together they make an interactive session.
  4. 4. You create a file in one container, then run docker run alpine:3.22 ls /file in a new command and it is missing. Why?

    Changes live in the writable layer of the first container. A new docker run starts from the pristine image. Use docker start on the old container, or a volume, to keep data.
  5. 5. Which exit code does a container usually report when the command you asked it to run does not exist in the image?

    127 means 'command not found'. 126 means found but not executable, 125 means Docker itself failed, and 137 means the process was killed with SIGKILL.

Summary

  • docker run IMAGE [COMMAND] pulls the image if needed, creates a container, starts it and streams its output.
  • A container lives as long as its main process; a stopped container still exists until you remove it with docker rm.
  • docker ps -a lists all containers, including stopped ones; --name gives a container a readable name.
  • --rm removes the container automatically on exit; the image stays on disk.
  • -it gives an interactive shell; use -i alone for piped input.
  • docker run always makes a new container; docker start restarts an existing one.
  • Exit code 127 means command not found, 126 not executable, 125 a Docker error, 137 SIGKILL.

Next: How Docker Works