如何为Docker Swarm服务创建的容器指定自定义命名规则?
Great question! I’ve run into this exact need before, so let’s break down what’s possible and the workarounds for your use case.
First, the straight answer: Docker Swarm does NOT support using templates to directly customize container names like you can with --hostname. Here’s why: Swarm’s service model treats containers as ephemeral, replaceable units managed by the orchestrator. Auto-generated container names (like serviceName.1.abcdef123456) guarantee uniqueness even when scaling services, restarting tasks, or rescheduling containers across nodes—something a custom template could easily break if not carefully designed.
That said, you have a couple of solid workarounds to achieve similar visibility and organization:
1. Use Custom Labels to Add Identifiers
Instead of renaming containers, attach a custom label that uses the same template logic you’d use for hostnames. This lets you filter and identify containers easily without conflicting with Swarm’s internal naming system.
Example command:
docker service create --name serviceName --replicas 2 --network skynet \ --hostname="{{.Node.Hostname}}-{{.Task.Slot}}" \ --label "custom.identifier={{.Node.Hostname}}-{{.Task.Slot}}" \ imageName
To view containers with this custom identifier, use filtered docker ps or formatted output:
# Filter containers by your custom label docker ps --filter "label=custom.identifier=node-1-1" # Show container names alongside your custom identifier docker ps --format "table {{.Names}}\t{{.Label.custom.identifier}}"
2. Map Task Metadata to Containers
Swarm’s built-in task metadata can help you link auto-generated container names to the slot/node info you care about. Use docker service ps to see the relationship between tasks, their slots, nodes, and corresponding containers:
docker service ps --format "table {{.Name}}\t{{.Node}}\t{{.Slot}}\t{{.Container}}" serviceName
Sample output:
NAME NODE SLOT CONTAINER serviceName.1 node-1 1 serviceName.1.abcdef123456 serviceName.2 node-2 2 serviceName.2.ghijkl678901
This makes it easy to trace which container belongs to which task slot or node, even without a custom container name.
Why This Design Choice?
Swarm prioritizes reliability and consistency over fully customizable container names. Auto-generated names eliminate the risk of duplicate names (a common issue when scaling) and ensure the orchestrator can always track and manage containers correctly. Labels and task metadata provide the flexibility you need without compromising Swarm’s core functionality.
内容的提问来源于stack exchange,提问作者Quinten Scheppermans

