Naming Docker Containers with --name
Learn how to assign meaningful names to Docker containers using the --name flag. Understand naming conventions, DNS resolution in Docker networks, and container management benefits.
Detailed Explanation
Why Container Names Matter
By default, Docker generates random two-word names like quirky_galileo or tender_morse. While amusing, these names are impractical for production environments. The --name flag lets you assign a meaningful, predictable name:
docker run -d --name api-gateway nginx
Naming Rules and Conventions
Docker container names must match the regex [a-zA-Z0-9][a-zA-Z0-9_.-] and be unique on the host. Common conventions include:
- Service-based:
web-server,api-gateway,cache-layer - Environment-prefixed:
prod-api,staging-db,dev-worker - Project-scoped:
myapp-frontend,myapp-backend,myapp-db
DNS Resolution in Docker Networks
Container names serve as hostnames within Docker networks. When containers are on the same user-defined network, they can reach each other by name:
docker network create mynet
docker run -d --name db --network mynet postgres:16
docker run -d --name app --network mynet my-app-image
Inside the app container, db resolves to the PostgreSQL container's IP address. This eliminates the need for hardcoded IP addresses and makes container configurations portable.
Managing Named Containers
Named containers are easier to manage because you can reference them predictably:
docker stop api-gateway
docker start api-gateway
docker restart api-gateway
docker logs api-gateway
docker exec -it api-gateway bash
The Uniqueness Constraint
Docker enforces name uniqueness per host. If a container named api-gateway already exists (even if stopped), you cannot create another with the same name. You must remove the old one first:
docker rm api-gateway # Remove stopped container
docker rm -f api-gateway # Force remove running container
A common pattern in scripts is to remove any existing container before creating a new one:
docker rm -f api-gateway 2>/dev/null
docker run -d --name api-gateway nginx
Best Practices
- Always name containers in production and CI/CD environments.
- Use consistent naming schemes across your team or organization.
- Avoid overly long names; keep them concise yet descriptive.
- Document your naming convention in your project's README or runbook.
Use Case
Setting up a multi-container development environment where services need to communicate by name, such as a web application connecting to a named database container on a shared Docker network.