Skip to content
shellhacks.dev
Docker

Give a container a name

Give a container a fixed name with docker run --name and refer to it in later commands. A second container with the same name is refused until the first goes.

1 min read
Summarize in AI

A container started in the background has a random generated name, and you want one you can type.

Shell
docker run -d --name demo-web alpine:3.20 sleep 60 >/dev/null
docker ps --filter name=demo-web --format '{{.Names}}'
docker run -d --name demo-web alpine:3.20 sleep 60 2>&1 | cut -c1-95
docker rm -f demo-web
Text
demo-web
docker: Error response from daemon: Conflict. The container name "/demo-web" is already in use

Run 'docker run --help' for more information
demo-web

--name sets the container's name, which then works anywhere an id does: docker logs, docker exec, docker stop. Names are unique on one daemon, so the second run is rejected, as the docker run reference implies. On a user-defined network the name is also the container's DNS name, so other containers reach it by it.

A name is held by the container even when it has stopped, so rerunning a script fails until docker rm removes the old one. Use docker rm -f first, or --rm so nothing is left. Compose adds a project prefix to names, so do not rely on a plain name there.

Taggeddocker
Share

More snippets

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
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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.