Running a container in the foreground (no -d)
By default,docker run attaches your terminal to the container’s STDOUT/STDERR. This is useful for debugging or when you want to see process output in real time. However, interrupting your terminal (for example with Ctrl+C) sends a termination signal to the container and causes it to exit.
Example: running the official nginx image in the foreground
Running a container in the background (detached mode)
Add the-d flag to docker run to start the container detached. Docker prints the container ID and returns you immediately to the shell; the container continues running in the background.
Example:
List running containers
To see containers that are currently running, use:- The full container ID is 64 hex characters; most commands accept the short form (first 4–12 characters) as long as it is unique.
- Docker assigns a human-readable container name (e.g.,
adoring_zhukovsky) if you don’t provide one. You can set a custom name with--name <name>when running the container.
Stopping a running container
Usedocker stop followed by the container ID, its short unique prefix, or its name.
Example:
docker ps will not list that container:
List all containers (including exited)
To view every container on the host — running and exited — usedocker ps -a.
Example:
Removing containers
Exited containers remain on disk until you explicitly remove them. Usedocker rm to delete container metadata and its writable layer. You can pass multiple IDs or names in one command.
Remove a single container (short ID):
docker ps -a will list only the containers that remain:
Quick reference — common container lifecycle commands
Detached containers still run in the background and produce logs. Use
docker logs <container> to inspect output, and docker exec -it <container> /bin/sh (or /bin/bash) to open an interactive shell inside a running container.Be careful when removing containers:
docker rm deletes container metadata and filesystem changes made in that container. If you need to preserve data, consider using volumes or committing the container to an image before removal.Links and references
- Docker documentation — containers: https://docs.docker.com/engine/reference/commandline/container_ls/
- docker run reference: https://docs.docker.com/engine/reference/commandline/run/