How to Use docker run --name to Name Containers
Use
docker run --name container_name image to start a Docker container with a custom name. This makes it easier to manage and reference the container instead of using the default container ID.Syntax
The docker run --name command lets you assign a custom name to a container when you start it. This name helps you identify and manage the container easily.
docker run: Starts a new container.--name container_name: Assigns a custom name to the container.image: The Docker image to create the container from.
bash
docker run --name mycontainer nginx
Example
This example runs an Nginx web server container named mynginx. You can then use this name to stop or inspect the container easily.
bash
docker run --name mynginx -d -p 8080:80 nginx docker ps --filter "name=mynginx"
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
abc123def456 nginx "/docker-entrypoint.…" 10 seconds ago Up 9 seconds 0.0.0.0:8080->80/tcp mynginx
Common Pitfalls
Common mistakes when using --name include:
- Using a name that is already taken by another container, which causes an error.
- Forgetting to use
--nameand ending up with a random container ID that is hard to remember. - Trying to use invalid characters in the name (only letters, digits, underscores, periods, and dashes are allowed).
bash
docker run --name mycontainer nginx # Trying to run again with the same name causes error: docker run --name mycontainer nginx # Correct approach: use a unique name docker run --name mycontainer2 nginx
Output
docker: Error response from daemon: Conflict. The container name "/mycontainer" is already in use by container "abc123def456". You have to remove (or rename) that container to be able to reuse that name.
Quick Reference
Tips for using docker run --name:
- Choose meaningful names to easily identify containers.
- Use
docker ps -a --filter "name=container_name"to find containers by name. - Remove containers with
docker rm container_namebefore reusing names.
Key Takeaways
Use
--name to assign a clear, custom name to your Docker container.Container names must be unique and use only allowed characters.
Named containers are easier to manage than using container IDs.
If a name is taken, remove or rename the existing container before reuse.
Use container names with Docker commands like
docker stop and docker rm.