Skip to content
shellhacks.dev
Docker

Run a throwaway container

Run a container once and remove it on exit with docker run --rm. Without the flag every run leaves a stopped container behind, one per invocation.

1 min read
Summarize in AI

A one-off command in a container leaves a stopped container on disk each time unless you ask for it to be deleted.

Shell
docker run --name demo-keep alpine:3.20 true
docker run --rm --name demo-gone alpine:3.20 true
docker ps -a --filter name=demo- --format '{{.Names}}'
docker rm demo-keep > /dev/null
Text
demo-keep

--rm tells the daemon to delete the container, and the anonymous volumes it created, as soon as its main process exits, which the docker run reference lists under the clean-up options. The listing shows that only the run without the flag is still on disk. Scripts and CI jobs that call docker run in a loop collect hundreds of stopped containers otherwise.

--rm cannot be combined with --restart, and the container's logs go with it, so a failure you want to inspect afterwards is gone. For a command you may need to debug, drop the flag while developing. A named volume is kept when the container is removed.

Taggeddocker
Share

More snippets

Docker

Mount read-only

Mount a host directory read-only into a container with -v "$PWD":/data:ro. A write from inside fails with a read-only file system error, even as root.

1 min read
Docker

Set environment variables

Set an environment variable in a container with docker run -e NAME=value. Pass -e NAME with no value to copy the value from the calling shell.

1 min read
Docker

Load environment from a file

Load variables from a file with docker run --env-file. The file is not parsed by a shell, so quotes stay in the value and a line with export fails.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.