# Docker Engine (Part 4)

Once Docker is installed and running on your machine, the **Docker CLI (**`docker`**)** becomes your primary interface for managing containers, images, networks, and volumes. However, beginners often hit common roadblocks early on—such as containers exiting immediately after starting, flags placed in the wrong order, or terminals getting locked in the foreground.

In this guide, we will break down modern vs. legacy Docker CLI syntax, walk through the full container lifecycle, and explain how interactive (`-it`) and detached (`-d`) execution modes work under the hood.

## 1\. Modern vs. Legacy Docker CLI Syntax

Every Docker command follows a structured hierarchy:

```plaintext
docker <object> <subcommand> [options] [arguments]
```

As Docker grew, its top-level CLI became crowded with dozens of commands. To keep things organized, Docker introduced **management commands** that group operations by object type (`container`, `image`, `network`, `volume`).

You will encounter both the **modern syntax** and the **legacy shorthand syntax** across official docs and tutorials. Both work identically:

<table style="min-width: 75px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p><strong>Operation</strong></p></td><td colspan="1" rowspan="1"><p><strong>Modern Object Syntax (Recommended)</strong></p></td><td colspan="1" rowspan="1"><p><strong>Legacy Shorthand Syntax</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Run a container</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container run &lt;image&gt;</code></p></td><td colspan="1" rowspan="1"><p><code>docker run &lt;image&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>List containers</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container ls</code></p></td><td colspan="1" rowspan="1"><p><code>docker ps</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Stop / Kill a container</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container stop &lt;id&gt;</code></p></td><td colspan="1" rowspan="1"><p><code>docker stop &lt;id&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Attach to a container</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container attach &lt;id&gt;</code></p></td><td colspan="1" rowspan="1"><p><code>docker attach &lt;id&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Build an image</strong></p></td><td colspan="1" rowspan="1"><p><code>docker image build .</code></p></td><td colspan="1" rowspan="1"><p><code>docker build .</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>List images</strong></p></td><td colspan="1" rowspan="1"><p><code>docker image ls</code></p></td><td colspan="1" rowspan="1"><p><code>docker images</code></p></td></tr></tbody></table>

## 2\. Creating, Inspecting, and Starting Containers

Managing a container's lifecycle happens in two distinct phases: **creating** the container filesystem/metadata, and **starting** its primary process.

### Step 1: Create a Container (`create`)

The `create` subcommand prepares a writable container layer from an image without actually starting it:

```json
docker container create httpd
```

- If `httpd` is not cached locally, Docker pulls it from **Docker Hub** first.
- Docker outputs a **64-character unique Container ID** (e.g., `11cb8f9a...`) and stores all container configuration and metadata on Linux under `/var/lib/docker/containers/<container-id>/`.
- Because you didn't specify a name, Docker automatically assigns a random two-word name (such as `charming_wiles` or `quizzical_austin`).

### Step 2: List Containers (`ls`)

By default, `docker container ls` only displays **currently running** containers. To see containers in *all* states (Created, Running, Exited), append `-a`:

```plaintext
# List only running containers
docker container ls

# List all containers (running, created, and stopped)
docker container ls -a
```

**Useful** `ls` **Flags:**

- `-l` — Show details of the most recently created container.
- `-q` — Quiet mode; output only the **12-character short Container IDs** (useful for scripting).
- `-aq` — Output short IDs for *all* containers, regardless of state.

### Step 3: Start a Created Container (`start`)

Start a created or stopped container using its name or unique ID prefix:

```plaintext
docker container start charming_wiles
```

(Tip: You never need to type all 64 characters of a Container ID. Typing the first **3 to 4 characters**—such as `11cb`—is enough, provided no other container on the host shares that prefix.)

## 3\. Combining Create + Start (`docker container run`)

In day-to-day workflows, you rarely run `create` and `start` separately. The `run` subcommand combines both steps into one:

```plaintext
docker container run httpd
```

### Why Does `docker container run ubuntu` Exit Immediately?

If you run a container using a base OS image like Ubuntu:

```plaintext
docker container run ubuntu
```

...and then check `docker container ls`, **nothing is running**. Checking `docker container ls -a` reveals the container is already in an `Exited (0)` state.

**Why does this happen?** Unlike Virtual Machines, **containers are not meant to boot an entire operating system**. A container is designed to run a **single foreground process** (a web server, API, database, or script). The container stays alive *only* as long as that primary process stays alive:

1. Base OS images like `ubuntu` or `alpine` launch `/bin/bash` (or `/bin/sh`) as their default command.
2. When started without an attached terminal, `bash` sees no standard input (`STDIN`), finishes immediately, and exits.
3. Because the container's main process exited, the container stops immediately.

## 4\. Running Interactive Containers (`-i` and `-t`)

To keep a shell-based container alive and interact with it, you must attach an interactive terminal session using two flags:

- `-i` **(**`--interactive`**):** Keeps `STDIN` open so you can send keystrokes into the container.
- `-t` **(**`--tty`**):** Allocates a pseudo-TTY (terminal driver) so the shell formats prompts and output properly.

Combine both flags as `-it`:

```plaintext
docker container run -it ubuntu
```

This drops you straight into the `bash` prompt inside the container (`root@<container-id>:/#`). As long as you remain inside that shell, `docker container ls` will show the container as `Up`. Typing `exit` terminates the `bash` process and stops the container.

### Critical Syntax Rule: Flag Placement Matters!

Always place Docker flags (`-it`, `-d`, `--name`) **before** the image name:

```plaintext
# CORRECT: Flags come BEFORE the image name
docker container run -it ubuntu

# INCORRECT: Flags placed AFTER the image name are treated as arguments inside the container
docker container run ubuntu -it
```

Anything written *after* the image name overrides the image's default startup command (for example, `docker container run ubuntu ls /etc` runs `ls /etc` inside Ubuntu and exits).

## 5\. Naming and Renaming Containers

Instead of relying on Docker's random names, assign meaningful names with `--name`:

```plaintext
docker container run -it --name webapp ubuntu
```

Each container name on a host must be unique. If you need to change a container's name later, use `rename`:

Bash

```plaintext
docker container rename webapp frontend-app
```

## 6\. Foreground (Attached) vs. Background (Detached) Mode

When you run a long-lived service like an Apache web server (`httpd`) without extra flags:

```plaintext
docker container run httpd
```

Docker runs the container in **attached (foreground) mode**. Your terminal is locked to the container's `STDOUT`/`STDERR` logs, and pressing `Ctrl + C` sends an interrupt signal that kills the container process.

### Running in the Background (`-d`)

To run a container in the background and immediately get your terminal prompt back, pass the `-d` **(**`--detach`**)** flag:

```plaintext
docker container run -d --name web-server httpd
```

Docker prints the full 64-character Container ID and returns control of your shell while `httpd` continues running in the background.

### Reattaching to a Background Container (`attach`)

If you ever want to reconnect your terminal to a running detached container's live output stream, use `attach`:

```plaintext
docker container attach web-server
# Or using the first 4 characters of its Container ID:
docker container attach 11cb
```

*(Note: Once reattached, pressing* `Ctrl + C` *will stop the container unless you detach cleanly using the escape sequence* `Ctrl + P` ***followed by*** `Ctrl + Q`*.)*

## Quick Command Cheat Sheet

<table style="min-width: 50px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p><strong>Task</strong></p></td><td colspan="1" rowspan="1"><p><strong>Command</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Create without starting</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container create &lt;image&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Run interactively (shell)</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container run -it --name &lt;name&gt; &lt;image&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Run in background</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container run -d --name &lt;name&gt; &lt;image&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>List running containers</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container ls</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>List all containers</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container ls -a</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Start / Stop container</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container start &lt;name_or_id&gt;</code> / <code>stop &lt;name_or_id&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Rename container</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container rename &lt;old_name&gt; &lt;new_name&gt;</code></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Reattach to background container</strong></p></td><td colspan="1" rowspan="1"><p><code>docker container attach &lt;name_or_id&gt;</code></p></td></tr></tbody></table>
