Docker Containerization Docker Swarm and Orchestration — Questions and Answers
Question 1: What command initializes a Docker Swarm on the current node?
- docker swarm init (Correct answer)
- docker swarm start
- docker swarm create
- docker cluster init
Correct answer: docker swarm init
docker swarm init initializes the current Docker Engine as a swarm manager node.
Running 'docker swarm init' on a node promotes it to a swarm manager. It generates a join token that worker nodes can use to join the swarm. You can optionally specify --advertise-addr to set the manager's advertised address when multiple interfaces are present.
Question 2: In Docker Swarm, what is the difference between a manager node and a worker node?
- Managers orchestrate services and maintain cluster state; workers only execute tasks (Correct answer)
- Managers handle networking; workers handle storage
- Managers run only one container; workers run many
- There is no functional difference
Correct answer: Managers orchestrate services and maintain cluster state; workers only execute tasks
Manager nodes maintain the swarm state using the Raft consensus algorithm and schedule tasks, while worker nodes only execute the assigned containers.
Manager nodes use the Raft distributed consensus algorithm to maintain a consistent, fault-tolerant cluster state. They schedule and dispatch tasks to worker nodes. Worker nodes receive task assignments and run containers, but do not participate in management decisions. For high availability, it is recommended to have an odd number of managers (3 or 5).
Question 3: Which command creates a new service in a Docker Swarm?
- docker service create (Correct answer)
- docker run --swarm
- docker deploy service
- docker swarm service add
Correct answer: docker service create
docker service create is used to create and deploy a new service within a Docker Swarm cluster.
The 'docker service create' command allows you to define a service by specifying the image, number of replicas, published ports, environment variables, and placement constraints. The swarm scheduler then distributes the service tasks (containers) across available worker nodes according to the defined constraints.
Question 4: What is the purpose of the --replicas flag when creating a Docker Swarm service?
- Specifies how many task instances of the service should run (Correct answer)
- Sets the number of manager nodes
- Defines how many volumes to create
- Controls how many networks the service joins
Correct answer: Specifies how many task instances of the service should run
The --replicas flag sets the desired number of running task instances (containers) for the service across the swarm.
When you run 'docker service create --replicas 3 nginx', the swarm scheduler ensures 3 replicated tasks of the nginx service are running at all times. If a node fails, the scheduler automatically reschedules tasks on other available nodes to maintain the desired replica count, providing high availability.
Question 5: How do you scale an existing Docker Swarm service to 5 replicas?
- docker service scale my-service=5
- docker service update --replicas 5 my-service
- docker swarm scale my-service 5
- Both A and B are correct (Correct answer)
Correct answer: Both A and B are correct
Both 'docker service scale my-service=5' and 'docker service update --replicas 5 my-service' achieve the same result of scaling the service to 5 replicas.
'docker service scale' is a convenience shorthand that sets the replica count. 'docker service update --replicas' is the more general update command that also supports other changes. Both are correct and commonly used. The swarm scheduler will add or remove tasks as needed to reach the desired state.
Question 6: What is an overlay network in Docker Swarm?
- A distributed network that spans multiple Docker hosts in a swarm (Correct answer)
- A network that only exists on a single host
- A network used exclusively for management traffic
- A read-only network for container inspection
Correct answer: A distributed network that spans multiple Docker hosts in a swarm
An overlay network spans multiple Docker hosts and enables containers on different nodes to communicate as if they were on the same local network.
Overlay networks use VXLAN encapsulation to create a virtual network that spans all nodes in the swarm. Containers attached to the same overlay network can communicate using service names as DNS hostnames regardless of which physical node they run on. The 'ingress' overlay network is automatically created for published port traffic.
Question 7: What does the docker stack deploy command do?
- Deploys a multi-service application defined in a Compose file to a swarm (Correct answer)
- Builds Docker images from source code
- Pushes images to a registry
- Updates a single service
Correct answer: Deploys a multi-service application defined in a Compose file to a swarm
docker stack deploy reads a Docker Compose (or stack) YAML file and deploys all defined services, networks, and volumes to the swarm as a named stack.
A Docker Stack is a collection of interrelated services that share networks and can be managed together. 'docker stack deploy -c docker-compose.yml my-stack' creates or updates all services defined in the compose file. It supports version 3+ Compose syntax with 'deploy' keys for replica counts, update policies, and resource limits.
Question 8: Which consensus algorithm does Docker Swarm use to maintain cluster state?
- Raft (Correct answer)
- Paxos
- Zab
- PBFT
Correct answer: Raft
Docker Swarm uses the Raft consensus algorithm among manager nodes to maintain a consistent and fault-tolerant cluster state.
The Raft algorithm ensures that manager nodes agree on the cluster state. With N managers, the swarm can tolerate (N-1)/2 manager failures. For example, 3 managers tolerate 1 failure; 5 managers tolerate 2 failures. An even number of managers is discouraged because it doesn't improve fault tolerance. Managers use an internal key-value store based on Raft.
Question 9: What is a Docker Swarm task?
- A single container instance running as part of a service (Correct answer)
- A scheduled cron job
- A background health check
- A Dockerfile build step
Correct answer: A single container instance running as part of a service
A task is the atomic unit of scheduling in Docker Swarm — it represents a running container that is part of a service.
When a service is created with 3 replicas, the swarm scheduler creates 3 tasks, each assigned to an available worker node. Each task maps to exactly one container. If a task fails, the scheduler creates a replacement task on the same or a different node. Tasks progress through states: pending → assigned → preparing → running → complete/failed.
Question 10: How do you retrieve the join token for worker nodes in a Docker Swarm?
- docker swarm join-token worker (Correct answer)
- docker swarm get-token worker
- docker swarm token --worker
- docker swarm info --token
Correct answer: docker swarm join-token worker
docker swarm join-token worker prints the command (including the token) that worker nodes need to run to join the swarm.
The join token is a secret value that authenticates a node joining the swarm. 'docker swarm join-token worker' shows the full join command. 'docker swarm join-token manager' shows the manager join command. Tokens can be rotated with 'docker swarm join-token --rotate worker' to invalidate old tokens if security is compromised.
Question 11: What is the default update policy behavior for a Docker Swarm service update?
- Rolling update: tasks are updated one at a time with a configurable delay (Correct answer)
- All tasks are stopped and restarted simultaneously
- Only failed tasks are updated
- Updates require manual approval for each node
Correct answer: Rolling update: tasks are updated one at a time with a configurable delay
By default, Docker Swarm performs a rolling update, replacing one task at a time and waiting before proceeding to the next, to maintain service availability.
The rolling update policy (--update-parallelism and --update-delay flags) ensures zero-downtime deployments. By default, one task at a time is updated with a 0-second delay. You can configure '--update-parallelism 2 --update-delay 10s' to update 2 tasks every 10 seconds. If an update fails, '--update-failure-action' can be set to 'pause' or 'rollback'.
Question 12: What command lists all services running in a Docker Swarm?
- docker service ls (Correct answer)
- docker swarm list
- docker ps --swarm
- docker stack services
Correct answer: docker service ls
docker service ls displays all services in the swarm along with their replica count, image, and ports.
'docker service ls' shows each service's ID, name, mode (replicated/global), number of running vs desired replicas, image, and published ports. To see individual tasks for a service, use 'docker service ps <service-name>'. This command must be run from a manager node.
Question 13: What is a global service in Docker Swarm?
- A service that runs exactly one task on every node in the swarm (Correct answer)
- A service accessible from the internet
- A service with unlimited replicas
- A service that spans multiple swarms
Correct answer: A service that runs exactly one task on every node in the swarm
A global service automatically schedules exactly one task on every active node, making it ideal for monitoring agents or log collectors that should run everywhere.
Created with 'docker service create --mode global', a global service ensures one task runs on each node, including new nodes that join the swarm later. Unlike replicated services, you cannot specify a replica count. Global services are commonly used for node-level infrastructure like Prometheus node exporters, Fluentd log agents, or antivirus scanners.
Question 14: How do you drain a node in Docker Swarm to prepare it for maintenance?
- docker node update --availability drain <node> (Correct answer)
- docker node stop <node>
- docker swarm drain <node>
- docker node remove --force <node>
Correct answer: docker node update --availability drain <node>
Setting a node's availability to 'drain' prevents new tasks from being scheduled on it and reschedules existing tasks to other nodes.
Running 'docker node update --availability drain <node-id>' gracefully moves all running tasks off the specified node. The swarm scheduler reschedules those tasks on other active nodes. Once maintenance is complete, you restore the node with '--availability active'. The node can still be a manager (participating in Raft) while drained.
Question 15: What is the ingress network in Docker Swarm used for?
- Routing external traffic to service tasks via the routing mesh (Correct answer)
- Internal service-to-service communication only
- Management plane traffic between managers
- Persistent volume mounts
Correct answer: Routing external traffic to service tasks via the routing mesh
The ingress network is a special overlay network that implements the swarm routing mesh, allowing any node to accept traffic for a published service port and route it to an available task.
The routing mesh uses IPVS load balancing to distribute incoming requests to any published port across all nodes, regardless of whether a task is running on that specific node. This means you can hit any node's IP on the published port and the swarm will route the request to an available task. The ingress overlay network carries this cross-node traffic.
Question 16: Which flag in docker service create pins a service to nodes with a specific label?
- --constraint (Correct answer)
- --filter
- --node-selector
- --placement
Correct answer: --constraint
The --constraint flag allows you to restrict task placement to nodes that match specific criteria such as node labels, engine labels, or node roles.
Example: 'docker service create --constraint node.labels.region==us-east nginx'. Constraints support equality (==) and inequality (!=). You can constrain by node.role (manager/worker), node.hostname, node.id, node.labels.*, and engine.labels.*. Labels are set with 'docker node update --label-add region=us-east <node>'.
Question 17: What happens to a swarm service's tasks if a worker node goes offline unexpectedly?
- The swarm scheduler automatically reschedules the tasks on other available nodes (Correct answer)
- The tasks are permanently lost and must be recreated manually
- The manager promotes another worker to take over the failed node's exact state
- The entire swarm pauses until the node comes back online
Correct answer: The swarm scheduler automatically reschedules the tasks on other available nodes
Docker Swarm continuously reconciles the desired state with the actual state, automatically rescheduling failed or orphaned tasks on healthy nodes.
The swarm manager monitors all nodes using heartbeats. When a node is detected as unreachable (after a configurable timeout), the manager marks all tasks on that node as failed and schedules replacement tasks on other available nodes. This self-healing behavior is one of Docker Swarm's core advantages for high availability.
Question 18: What is the purpose of docker secret in Docker Swarm?
- Securely stores sensitive data like passwords and certificates, delivering them only to authorized service tasks (Correct answer)
- Encrypts Docker images in the registry
- Hides service names from other containers
- Encrypts overlay network traffic
Correct answer: Securely stores sensitive data like passwords and certificates, delivering them only to authorized service tasks
Docker secrets are encrypted at rest in the swarm's Raft store and decrypted only in memory on the node running an authorized task, never written to disk in plaintext.
Secrets are created with 'docker secret create my-secret secret-value.txt'. Services are granted access with '--secret my-secret', which mounts the secret at /run/secrets/my-secret inside the container. Secrets are encrypted with AES-256 in the Raft log and only transmitted over TLS to the specific nodes running authorized tasks.
Question 19: How do you remove a node from a Docker Swarm cluster?
- Run 'docker swarm leave' on the node, then 'docker node rm' on the manager (Correct answer)
- Run 'docker node delete' from the manager
- Run 'docker swarm remove <node>' from the manager
- Power off the node; it is removed automatically
Correct answer: Run 'docker swarm leave' on the node, then 'docker node rm' on the manager
First run 'docker swarm leave' on the node itself to gracefully exit, then remove it from the manager's node list with 'docker node rm'.
A node must leave the swarm with 'docker swarm leave' (use --force for managers). After leaving, the manager still shows the node in a 'down' state. Run 'docker node rm <node-id>' on a manager to fully remove it from the cluster listing. Attempting to remove a manager requires '--force' flag and ensuring a quorum is maintained.
Question 20: What is a Docker config object (docker config) used for?
- Stores non-sensitive configuration data and makes it available to swarm services (Correct answer)
- Stores encrypted passwords for services
- Defines network topology for the swarm
- Manages CPU and memory limits
Correct answer: Stores non-sensitive configuration data and makes it available to swarm services
Docker configs store non-sensitive configuration files (like nginx.conf) in the swarm and mount them into service containers, similar to secrets but without encryption.
Created with 'docker config create my-config config.yml', a config is stored in the Raft log (unencrypted) and can be mounted into service containers with '--config src=my-config,target=/etc/app/config.yml'. This avoids baking configuration into images, making services more portable and configurable without image rebuilds.
Question 21: Which command rolls back a Docker Swarm service to its previous configuration?
- docker service rollback <service>
- docker service update --rollback <service>
- docker service revert <service>
- Both A and B are correct (Correct answer)
Correct answer: Both A and B are correct
Both 'docker service rollback' and 'docker service update --rollback' revert a service to its previous specification.
Docker Swarm maintains the previous service configuration so it can be quickly reverted. Rollback uses the same rolling update mechanism with --rollback-parallelism and --rollback-delay settings. This is useful after a bad deployment. You can configure automatic rollback on failure with '--update-failure-action rollback'.
Question 22: What does the docker node ls command display?
- All nodes in the swarm with their status, availability, and role (Correct answer)
- All containers running on the local node
- All services and their replica counts
- Network interfaces on each node
Correct answer: All nodes in the swarm with their status, availability, and role
docker node ls, run from a manager, lists every node in the swarm showing ID, hostname, status (Ready/Down), availability (Active/Drain/Pause), and manager status.
The output includes a '*' next to the current node. Manager status shows 'Leader' for the current Raft leader, 'Reachable' for other managers, and is blank for workers. The Availability column shows whether new tasks can be scheduled on the node. This command must be run on a manager node.
Question 23: How does Docker Swarm handle service discovery between services?
- Through embedded DNS: services are reachable by their service name on the same overlay network (Correct answer)
- Through a dedicated etcd cluster
- Through static IP assignments written to /etc/hosts
- Services must communicate via the host's public IP
Correct answer: Through embedded DNS: services are reachable by their service name on the same overlay network
Docker Swarm's embedded DNS server resolves service names to the VIP (Virtual IP) or to individual task IPs, enabling container-to-container communication by service name.
Each service gets a Virtual IP (VIP) that load-balances across all healthy tasks. Containers on the same overlay network can reach a service using its name as a hostname (e.g., http://my-api:8080). Docker's embedded DNS server handles the resolution. You can also use dnsrr (DNS round-robin) mode instead of VIP for direct task IP resolution.
Question 24: What resource limits can be set on a Docker Swarm service?
- CPU and memory limits and reservations (Correct answer)
- Only memory limits
- Only CPU limits
- Disk I/O and network bandwidth only
Correct answer: CPU and memory limits and reservations
Docker Swarm supports both CPU and memory limits (hard maximum) and reservations (guaranteed minimum) for service tasks.
Use '--limit-cpu 0.5 --limit-memory 128m' to cap a task's resource usage. Use '--reserve-cpu 0.25 --reserve-memory 64m' to guarantee resources for scheduling decisions. The scheduler only places tasks on nodes that have sufficient reserved capacity available. This prevents resource starvation and ensures predictable performance.
Question 25: What is the routing mesh in Docker Swarm?
- A load-balancing feature that routes external traffic to any available service task, regardless of which node it runs on (Correct answer)
- A physical network topology requirement
- A dedicated network for manager communication
- A routing protocol for inter-swarm communication
Correct answer: A load-balancing feature that routes external traffic to any available service task, regardless of which node it runs on
The routing mesh allows published service ports to be accessible on every swarm node, with traffic automatically load-balanced to a running task.
With the routing mesh, publishing port 80 for a web service means you can send requests to port 80 on ANY node's IP, even if that node has no task running for that service. IPVS handles the kernel-level load balancing. This simplifies external load balancer configuration since all nodes become valid backend endpoints.
Question 26: What minimum number of manager nodes is recommended for a production Docker Swarm to tolerate one manager failure?
- 3 (Correct answer)
- 2
- 4
- 5
Correct answer: 3
With 3 managers, the Raft quorum requires 2 (majority), so 1 manager failure can be tolerated while maintaining cluster operability.
Raft requires a quorum of (N/2)+1 managers to function. With 3 managers, quorum = 2, tolerating 1 failure. With 5 managers, quorum = 3, tolerating 2 failures. Having 2 or 4 managers doesn't improve fault tolerance compared to 1 and 3 respectively. For most production setups, 3 managers is the recommended configuration.
Question 27: Which placement preference strategy distributes swarm service tasks evenly across node labels?
- --placement-pref spread (Correct answer)
- --constraint even-spread
- --balance label
- --distribute-by label
Correct answer: --placement-pref spread
The --placement-pref 'spread' strategy distributes tasks evenly across the values of a specified node attribute, such as data center or availability zone.
Example: 'docker service create --placement-pref spread=node.labels.datacenter nginx'. If nodes are labeled datacenter=us-east and datacenter=eu-west, tasks will be spread evenly between them. This differs from constraints (which restrict placement) — preferences are best-effort and don't prevent scheduling if the preferred distribution isn't possible.
Question 28: What does 'docker service ps <service>' show?
- The individual tasks (containers) for the service, their state, and which node they run on (Correct answer)
- The resource usage of the service
- The network configuration of the service
- The service's environment variables
Correct answer: The individual tasks (containers) for the service, their state, and which node they run on
docker service ps lists each task for the service including its ID, name, image, node assignment, desired state, current state, and any error messages.
The output shows both currently running tasks and recently failed/completed tasks (for debugging). The 'Current State' column shows the task lifecycle (preparing, running, failed, etc.) and how long it's been in that state. The 'Error' column shows failure reasons. This is the primary tool for diagnosing service deployment issues.
Question 29: How can you force a Docker Swarm service to rebalance its tasks across nodes?
- docker service update --force <service> (Correct answer)
- docker swarm rebalance
- docker service rebalance <service>
- Swarm automatically rebalances without any command
Correct answer: docker service update --force <service>
docker service update --force causes the service to reschedule all tasks even if nothing else has changed, effectively rebalancing across available nodes.
Docker Swarm does NOT automatically rebalance tasks when new nodes join. If you add nodes to improve capacity, existing services won't redistribute their tasks. Running 'docker service update --force my-service' triggers a rolling update that reschedules tasks, allowing the scheduler to place them on the new, less-loaded nodes.
Question 30: What is a named volume in Docker Swarm, and what is a key limitation?
- A persistent volume that can be referenced by name, but does NOT automatically sync data across different swarm nodes (Correct answer)
- A volume that is replicated across all swarm nodes automatically
- A volume only accessible to manager nodes
- A temporary volume created per task that is deleted when the task ends
Correct answer: A persistent volume that can be referenced by name, but does NOT automatically sync data across different swarm nodes
Named volumes in Swarm persist data on the local node but are not automatically shared between nodes — a task rescheduled to a different node won't have access to the original data.
For stateful services in Swarm, you need a distributed storage solution (NFS, Ceph, GlusterFS, or cloud provider volumes) or use volume plugins that support multi-host access. Alternatively, use --mount with 'type=volume,volume-driver=<distributed-driver>'. Without this, scaling stateful services can cause data inconsistency because each node creates its own local volume.
Question 31: What is the purpose of the 'docker node promote' command?
- Promotes a worker node to a manager node (Correct answer)
- Increases a node's resource allocation
- Promotes a service to a higher priority
- Upgrades Docker Engine on a node
Correct answer: Promotes a worker node to a manager node
docker node promote converts a worker node into a manager node, adding it to the Raft consensus group and giving it orchestration capabilities.
Run 'docker node promote <node-id>' from an existing manager. The promoted node joins the Raft consensus group and can now schedule services. The reverse is 'docker node demote'. For high availability, you should promote nodes before draining/removing an existing manager to maintain quorum. Promote an odd number of managers total.
Question 32: How do you inspect the detailed configuration of a Docker Swarm service?
- docker service inspect <service> (Correct answer)
- docker service describe <service>
- docker inspect service/<service>
- docker service config <service>
Correct answer: docker service inspect <service>
docker service inspect returns the full JSON specification of a service including its image, replicas, networks, ports, resources, update config, and labels.
Use 'docker service inspect --pretty <service>' for a human-readable output instead of raw JSON. The output includes the service's creation time, current desired state, update/rollback policies, endpoint spec (published ports), and resource limits. This is useful for auditing service configurations or scripting configuration comparisons.
Question 33: What environment variable or mechanism do Swarm services use to discover other services at runtime?
- DNS resolution via service name on the shared overlay network (Correct answer)
- The SWARM_SERVICE_ADDRESSES environment variable
- The /etc/swarm-peers file injected by the manager
- A dedicated service registry like Consul (required by Swarm)
Correct answer: DNS resolution via service name on the shared overlay network
Services discover each other through Docker's built-in DNS: a service named 'database' is resolvable as 'database' by any container on the same overlay network.
Docker Swarm includes an embedded DNS server that handles service discovery automatically. No external service registry is required. When a container queries the DNS for a service name, it receives the service's VIP, which is then load-balanced to a healthy task. This works transparently for any DNS-based networking code.
Question 34: What is the 'desired state' concept in Docker Swarm?
- The declared configuration of a service that the swarm continuously reconciles with the actual running state (Correct answer)
- The maximum resource usage a service is allowed
- The node configuration saved before maintenance
- The Docker image tag pinned for a service
Correct answer: The declared configuration of a service that the swarm continuously reconciles with the actual running state
Docker Swarm is a declarative system — you define the desired state (e.g., 3 replicas of nginx:latest on port 80) and the orchestrator continuously works to maintain that state.
The desired state is stored in the Raft log. The swarm manager's reconciliation loop continuously compares the actual state (running tasks, node health) with the desired state and takes corrective action: starting new tasks if replicas are missing, stopping excess tasks, or rescheduling tasks from failed nodes. This loop runs continuously, not just at deployment time.
Question 35: Which Docker Swarm feature allows you to update a service without downtime?
- Rolling updates with --update-parallelism and --update-delay (Correct answer)
- Blue-green deployment (built-in)
- Canary releases using traffic splitting
- Zero-downtime updates are not supported natively
Correct answer: Rolling updates with --update-parallelism and --update-delay
Rolling updates gradually replace old service tasks with new ones, controlling parallelism and delay between batches to maintain service availability throughout the update.
With '--update-parallelism 1 --update-delay 30s', the swarm updates one task at a time, waiting 30 seconds between each. The new task must reach a running state before the next batch starts (configurable via --update-monitor and --update-max-failure-ratio). This ensures that a percentage of tasks remain available during the entire update process.
Question 36: What is the difference between 'docker stack rm' and 'docker service rm'?
- docker stack rm removes all services, networks, and configs in a stack; docker service rm removes a single service (Correct answer)
- They are identical commands
- docker stack rm only removes networks; docker service rm removes containers
- docker stack rm requires a compose file; docker service rm does not
Correct answer: docker stack rm removes all services, networks, and configs in a stack; docker service rm removes a single service
docker stack rm is the stack-level command that tears down everything deployed by 'docker stack deploy', while docker service rm removes only a single named service.
When you remove a stack, Docker removes all services defined in that stack's compose file, as well as any networks created for the stack (but not external networks). Volumes are NOT removed by default. 'docker service rm' is more surgical, removing exactly the one specified service. Use stack commands to manage stack-deployed resources as a unit.
Question 37: How can you check logs from all tasks of a Docker Swarm service?
- docker service logs <service> (Correct answer)
- docker logs --swarm <service>
- docker swarm logs <service>
- docker logs --all-tasks <service>
Correct answer: docker service logs <service>
docker service logs aggregates and streams logs from all running (and recently stopped) tasks of a service, with options to follow, timestamp, and filter by task.
'docker service logs -f my-service' follows live log output from all tasks. Use '--tail 100' to limit output, '--timestamps' to add timestamps, and '--no-task-ids / --no-trunc' to control task ID display. Logs from all nodes are streamed to the manager and presented in a unified view, making debugging distributed services much easier.
Question 38: What is Docker Swarm mode's approach to TLS and certificate management?
- Swarm automatically generates a CA and mutual TLS certificates for all node communication (Correct answer)
- TLS must be configured manually by the operator
- Swarm uses pre-shared keys instead of certificates
- Only manager-to-manager communication is encrypted
Correct answer: Swarm automatically generates a CA and mutual TLS certificates for all node communication
When you initialize a swarm, Docker automatically creates an internal CA and issues TLS certificates to all nodes, rotating them every 90 days by default.
Every node in the swarm has a TLS certificate signed by the swarm CA, enabling mutual authentication and encrypted communication between all nodes. Certificate rotation period can be changed with 'docker swarm update --cert-expiry'. Certificates are stored at /var/lib/docker/swarm/certificates/. You can also bring your own external CA for compliance requirements.
What command initializes a Docker Swarm on the current node?