CodeBlanks Logo Icon CodeBlanks

Naming containers

Learn to name a container with --name.

Naming

If no name is given, Docker generates a random one like jolly_tesla. Giving a meaningful name with --name lets you write later commands without copying IDs. The name must be unique:

$ docker run -d --name db postgres:16
$ docker run -d --name db postgres:16
docker: Error response from daemon: Conflict. The container name "/db" is already in use

Renaming and hostname

docker rename changes the name of an existing container. The hostname seen inside the container is by default the first 12 characters of the ID; it is set with --hostname:

docker rename db db_eski
docker run --rm --hostname derleyici alpine hostname
# derleyici

Practice Free the name

Write three commands: rename the existing db container to db_eski; start a new container named db from the postgres:16 image in the background with the environment variable POSTGRES_PASSWORD=gizli; list the running containers.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker rename db db_eski
docker run -d --name db -e POSTGRES_PASSWORD=gizli postgres:16
docker ps

Expected output

a7b8c9d0e1f2
CONTAINER ID   IMAGE         STATUS         NAMES
a7b8c9d0e1f2   postgres:16   Up 2 seconds   db

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the "The container name is already in use" error fixed?

  • The old container is removed or a different name is given Correct answer
  • The image is pulled again
  • Docker is reinstalled
  • The port is changed

Explanation: A stopped container still keeps its name.

2 Change the container's name.

Question
docker ____ db db_eski
Answer
docker rename db db_eski

Explanation: docker rename old new.

3 Match.

Term Meaning
--name Container name
--hostname Name seen inside
docker rename Changes the name
jolly_tesla Random name

All lessons in Beginner