Skip to content

Container Management (run, list, remove and more)


Container management is the core of day-to-day Docker operations. Whether you are spinning up temporary test environments, inspecting existing workloads, or cleaning up abandoned instances, understanding Docker’s container lifecycle commands is essential.

This guide walks through container creation, execution, inspection, state transitions, and removal, along with common CLI mistakes and flag placement pitfalls.

Container Lifecycle and State Transitions

Docker containers transition through explicit operational states based on the command executed.

    stateDiagram-v2
    direction TB
    [*] --> Image
    
    Image --> Created : docker container create
    Image --> Running : docker container run
    
    Created --> Running : docker container start
    
    state Running {
        [*] --> ProcessRunning
        ProcessRunning --> ProcessRunning : docker container exec
    }
    
    Running --> Exited : Process Exit / Stop / Kill
    Exited --> Running : docker container start
    
    Exited --> [*] : docker container rm / prune
    Running --> [*] : docker container rm -f
  

Detailed Command Transitions

    flowchart TD
    A[Image in Repository/Local Cache] -->|docker container create| B[State: Created]
    A -->|docker container run| C[State: Running]
    
    B -->|docker container start| C
    
    C -->|docker container exec| C
    C -->|docker container attach| C
    
    C -->|Process Ends / Exit Command| D[State: Exited]
    
    D -->|docker container start -ai| C
    D -->|docker container rm| E[Container Deleted]
    D -->|docker container prune| E
    
    C -->|docker container rm -f| E
  

Command Syntax: Modern vs. Legacy

Docker provides two command formats:

  1. Management Syntax (Recommended): docker container <command>
  2. Legacy Syntax: docker <command>

Modern Docker CLI uses structured management commands (docker container, docker image, docker network). Using docker container <command> makes your scripts and terminal workflows clear, explicit, and self-documenting.

Modern CommandLegacy EquivalentPrimary Purpose
docker container rundocker runCreate and start a new container from an image
docker container lsdocker psList active containers
docker container startdocker startStart a stopped container
docker container execdocker execExecute a command in a running container
docker container rmdocker rmRemove one or more containers

Core Lifecycle: Create, Start, and Run

Understanding the difference between creating, starting, and running containers prevents unexpected exits and syntax errors.

1. docker container create

Initializes a container from an image and prepares its filesystem/configuration without executing its main process. The container remains in the Created state.

docker container create --name my_app ubuntu

Note

If the container’s primary process is interactive (such as /bin/bash — default for ubuntu here), you should create with interactive flag (-it) so that you can later attach it when starting the container.

docker container create -it --name my_app ubuntu /bin/bash

2. docker container start

Boots up an existing container that is currently in a Created or Exited state.

docker container start my_app

Note

If the container’s primary process (such as /bin/bash) runs non-interactively without a persistent foreground task, the container will execute and exit immediately. To attach interactively upon starting, pass the -ai flags:

docker container start -ai my_app

3. docker container run

A convenience command that performs both create and start in a single step. If the required image is not present locally, Docker pulls it automatically before running.

docker container run -it ubuntu /bin/bash

Note

You only need interactive flag (-it) if you’re running interactive command like /bin/bash. For commands like echo using it is no-op.

docker container run ubuntu echo 'Non-Interactive Mode! No `-it` flag'

Key Distinctions: start vs. run vs. exec

It is common to confuse start, run, and exec. Here is how they differ:

  • docker container run: Operates on an image to launch a brand new container instance.
  • docker container start: Operates on an existing stopped container to resume its primary process (PID 1).
  • docker container exec: Operates on an already running container to spawn a new, secondary process alongside the primary process.

Interacting with Containers: attach vs. exec

Once a container is running, you can interact with it using either attach or exec.

docker container attach

Connects your terminal’s standard input, output, and error streams directly to the container’s primary running process (PID 1).

docker container attach my_container

Warning

If you run exit inside an attached shell session where /bin/bash is PID 1, the container will stop. To detach without stopping the container, press Ctrl+P followed by Ctrl+Q.

docker container exec

Spawns a separate process inside an active container. It is ideal for troubleshooting or running quick diagnostic commands.

# Run a single background command inside a container
docker container exec my_container echo "Health check passed!"

# Open an interactive secondary shell
docker container exec -it my_container /bin/bash

Listing and Managing Containers

Listing Containers (ls)

To view active (running) containers:

docker container ls

To view all containers regardless of status (Created, Running, Exited):

docker container ls -a

Example Output:

CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     NAMES
7f0c456b745b   ubuntu    "/bin/bash"   2 minutes ago   Created                    WebServer
347eb3a4a1d9   ubuntu    "/bin/bash"   5 minutes ago   Exited (0) 2 minutes ago   app_test
c5dc69e99345   ubuntu    "sleep 300"   8 minutes ago   Up 8 minutes               nice_wright

To output only container IDs (useful for scripts):

docker container ls -aq

Renaming Containers

If Docker generated a random name or you want to update a container’s identifier (name):

docker container rename old_name new_name

Removal and Cleanup

Accumulating stopped containers consumes disk space and clutters management logs.

Removing Specific Containers (rm)

To remove a stopped container:

docker container rm container_id_or_name

To forcibly stop and remove a running container:

docker container rm -f container_id_or_name

Bulk Cleanup (prune vs. Command Substitution)

Option 1: Remove all stopped containers

The prune command safely removes all containers in an Exited or Created state without touching running instances.

docker container prune

To bypass the confirmation prompt:

docker container prune --force

Option 2: Remove ALL containers (Stopped & Running)

Combine rm -f with command substitution to wipe out every container on the daemon:

docker container rm -f $(docker container ls -aq)

Common Pitfalls and Gotchas

1. Incorrect Argument Placement

Docker requires flags to appear before the image name. Any arguments placed after the image name are treated as commands to run inside the container.

  • Incorrect: docker container run ubuntu -it echo hi

    • Error: exec: "-it": executable file not found in $PATH (Docker thinks -it is a command inside Ubuntu).
    • Correct: docker container run -it ubuntu echo hi
  • Incorrect: docker container create ubuntu --name WebServer

    • Result: The container is created with a random name, and --name WebServer is set as the startup command.
    • Correct: docker container create --name WebServer ubuntu

2. Passing Unsupported Flags to docker container start

Flags like -d (detached) or -t (TTY) belong to run or create, not start.

  • Incorrect: docker container start -d container_id
    • Error: unknown shorthand flag: 'd' in -d
    • Correct (Interactive Start): docker container start -ai container_id
    • Correct: docker container start container_id

3. Attaching to Stopped Containers

You cannot attach standard streams to a container that is not running.

  • Attempt: docker container attach stopped_container
    • Error: cannot attach to a stopped container, start it first
    • Fix: Start the container first (docker container start container_id), or start and attach simultaneously with docker container start -ai container_id.

4. Running exec on Non-Existent or Stopped Containers

exec targets active instances. Recheck the container name/ID position in your command.

  • Incorrect: docker container exec echo "Hello"
    • Error: No such container: echo (Docker interpreted echo as the container name).
    • Correct: docker container exec container_id echo "Hello"

Summary Cheat Sheet

TaskCommand
Create container without startingdocker container create --name <name> <image>
Run temporary container interactivelydocker container run -it --rm <image> /bin/bash
Run container in backgrounddocker container run -d <image> <command>
Start stopped container interactivelydocker container start -ai <name_or_id>
Execute command in running containerdocker container exec -it <name_or_id> /bin/bash
List running containersdocker container ls
List all containersdocker container ls -a
Rename containerdocker container rename <old_name> <new_name>
Remove all stopped containersdocker container prune -f
Force remove all containersdocker container rm -f $(docker container ls -aq)
Last updated on