Intro
Docker Context is a powerful tool for managing multiple Docker environments, but in production, it becomes a critical link between your workstation and live infrastructure. A misconfigured context can send commands to the wrong cluster, expose secrets, or leave services broken after a failed deploy. This article gives you a practical, production-focused checklist for Docker Context operations, with concrete commands, real-world signals, and recovery steps.
We'll cover environment inventory, safe configuration, verification, common failure modes, and maintenance. Whether you're a developer supporting production, a DevOps consultant, or a startup team, you'll find actionable guidance to keep your Docker Contexts reliable and secure.
Version and Environment Inventory
Before touching any Docker Context, know exactly what you're working with. This means recording the Docker Engine version, context endpoints, active nodes, and how your environment is laid out.
Check Docker version and context list
docker version
Expected output includes the client and server versions. If the server endpoint is unreachable, you'll see an error here. Then check your contexts:
docker context ls
Example output:
NAME TYPE DESCRIPTION DOCKER ENDPOINT KUBERNETES ENDPOINT ORCHESTRATOR
local moby Current local context unix:///var/run/docker.sock
prod-swarm swarm Production Swarm cluster ssh://[email protected]
Look for the context marked with an asterisk (*) indicating the active one. A common mistake is running commands against the wrong context. Always verify the active context before any destructive operation:
docker context show
If the output doesn't match your intended environment, switch explicitly:
docker context use prod-swarm
Inventory running containers and services
Once you know the context, check what's running. This read-only observation should be your first step before any change.
For standalone containers:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
This outputs a clean table of container names, status, and port mappings. For production, you likely use Swarm or Compose. For Swarm services:
docker service ls
For Compose projects (run from the directory with your docker-compose.yml):
docker compose ps
Pay attention to services that are not in a "Running" state or have restart counts increasing. A container that keeps restarting is a classic sign of a misconfiguration or missing dependency.
Inspect a specific container or service
When you need details on mounts, networks, environment variables, or health status:
docker inspect <container-name>
For a Swarm service, use:
docker service inspect --pretty <service-name>
The --pretty flag prints the specification in a more readable format. Look for volume mounts, secrets, and healthcheck definitions.
Understand data persistence
Before changing anything that affects data, confirm where files are stored. This is critical for production. Two common patterns:
- Named volume: e.g.,
app_data:/var/lib/app. Managed by Docker, survives container recreation, and is portable across hosts (with care). - Bind mount: e.g.,
./data:/var/lib/app. Maps a host directory directly, useful for development but can cause permission and portability issues in production if the same path isn't on every node.
Check your volumes:
docker volume ls
Inspect a specific volume:
docker volume inspect app_data
The output shows the mountpoint on the host. For bind mounts, inspect the container or service to see the source path:
docker inspect <container-name> --format '{{json .Mounts}}'
If the source path doesn't exist on the host, the container will fail to start. Always ensure host directories exist and have correct permissions before deploying.
Restart test
A simple production-like test is to recreate a container and confirm it still has its data. For a standalone container:
docker stop <container-name>
docker rm <container-name>
# Then recreate using the same command or compose file, e.g.:
docker run -d --name <container-name> -v app_data:/var/lib/app your-image
Or with Compose:
docker compose up -d --force-recreate <service-name>
After recreation, check logs and verify data accessibility. If the data is gone, the service was likely writing to the container's ephemeral filesystem instead of a persistent volume. This is a common production pitfall.
Safe Configuration Path
Configuration changes to Docker Contexts should be deliberate, scoped, and reversible. The goal is to avoid breaking your ability to manage production while maintaining security.
Review current context configuration
To see the full details of a context, use:
docker context inspect prod-swarm
This returns JSON with fields like docker.endpoint, docker.ca, docker.cert, and docker.key. Pay attention to paths for certificates. Misconfigured TLS material is a frequent cause of context failures.
Create a new context safely
Never modify a working production context directly; create a new one and test it before switching.
For a direct SSH connection (recommended for Swarm):
docker context create prod-swarm-test --docker "host=ssh://[email protected]"
For a Docker API endpoint with TLS:
docker context create prod-api-test \
--docker "host=tcp://10.0.0.10:2376,ca=/path/to/ca.pem,cert=/path/to/cert.pem,key=/path/to/key.pem"
Then verify the connection:
docker --context prod-swarm-test ps
If this works, you can safely switch with docker context use prod-swarm-test. If it fails, delete the test context without affecting production:
docker context rm prod-swarm-test
Protect credentials and secrets
Never embed secrets in context definitions or shell scripts. Use environment variables or secret management tools. For certificates, ensure file permissions are restrictive:
chmod 600 /path/to/key.pem
For SSH contexts, use SSH agent forwarding or key-based authentication with passphrase, and avoid password authentication.
Change context endpoints with minimal blast radius
If you need to update a context's endpoint, export the existing config first:
docker context export prod-swarm > prod-swarm.dockercontext
This creates a backup you can re-import if needed:
docker context import prod-swarm prod-swarm.dockercontext
Then update the context with docker context update:
docker context update prod-swarm --docker "host=ssh://[email protected]"
Test before switching:
docker --context prod-swarm ps
If the new endpoint fails, you still have the old context file to restore.
Configuration best practices for Docker Context in production
- Use descriptive names for contexts, e.g.,
prod-eu-swarm,prod-us-swarm,staging. - Avoid using the default
localcontext for production work; create explicit contexts. - Document each context in your runbook: endpoint, purpose, owner.
- Regularly review contexts and remove unused ones to reduce confusion.
Verification and Diagnostics
After any configuration change, verification is mandatory. Here's how to systematically check your Docker Context and the applications it manages.
Check context connectivity
The simplest verification:
docker context use prod-swarm
docker info
docker info returns server details. If it hangs or errors, connectivity is broken. For SSH contexts, test SSH directly:
ssh [email protected] 'docker version --format "{{.Server.Version}}"'
Verify service health
For containers:
docker ps --filter "health=unhealthy"
This shows only unhealthy containers. If you have healthchecks defined, you'll see the health status in docker ps output. If a container is unhealthy, inspect its healthcheck log:
docker inspect --format '{{json .State.Health}}' <container-name>
For Swarm services:
docker service ps <service-name>
Look for tasks in "Running" state. If there are failures in the task history (e.g., "Failed" or "Rejected"), inspect the specific task:
docker service ps --no-trunc <service-name>
And check logs:
docker service logs <service-name> --tail 50
Diagnose common issues
- Context points to wrong endpoint: You run
docker psand see containers that don't look right. Fix:docker context show, switch if necessary. - Certificate expired: Error persists "x509: certificate has expired or is not yet valid". Fix: Renew certificates and update context with new paths.
- SSH connection drops: Error "ssh: handshake failed" or timeouts. Fix: Check network, SSH daemon, and credentials.
- Application not responding: After deploying, check logs and healthchecks. If healthcheck is misconfigured, update the Dockerfile or compose file.
Use Docker Desktop for diagnostics
If you use Docker Desktop, the GUI provides a visual overview of contexts and running containers. But for scripting and repeatability, rely on CLI commands documented here.
Failure Modes and Recovery
Even with careful planning, failures happen. Here are common Docker Context failure modes, their symptoms, and recovery steps.
Failure: Losing access to production due to misplaced context file
Symptoms: docker context ls shows missing context, or docker context use prod-swarm errors. You may have accidentally deleted a context or your Docker config directory ~/.docker was corrupted.
Recovery:
- If you exported a backup (see Safe Configuration Path), re-import it.
- If not, recreate the context manually using the known endpoint and certificates.
- Document the context creation steps in your runbook to make this quick.
Failure: Certificate rotation breaks context
Symptoms: Commands fail with TLS errors even though the endpoint is reachable.
Recovery:
- Update the context with new certificate paths.
- Test with
docker --context <name> psbefore relying on it. - If certificates are managed by a secrets store, ensure files are updated on the client machines.
Failure: Application data loss after container recreation
Symptoms: After running docker compose up -d --force-recreate, the application shows missing data or starts fresh.
Recovery:
- Stop the container immediately.
- Check if a volume or bind mount was used:
docker inspect <container> --format '{{json .Mounts}}'. - If the mount was missing, check the compose file for volume definitions. Correct the mount and redeploy.
- If data was written to the container layer, it's gone unless you have a backup. This underscores the importance of persistent storage.
Failure: Wrong context used for destructive command
Symptoms: You deleted or updated something on the wrong environment. E.g., docker stack rm on production when you thought you were on staging.
Recovery:
- This is difficult. If you have infrastructure-as-code or backups, restore.
- Prevent by always checking
docker context showbefore destructive commands. - Use context names that clearly indicate environment, and consider using shell prompts that display the current context.
Failure: SSH key rotation
Symptoms: SSH-based contexts fail authentication.
Recovery:
- Update your SSH key on the target nodes.
- Ensure your local SSH agent is running and the new key is added.
- Test SSH manually:
ssh [email protected]before testing the context.
Operations Checklist
This section condenses the guidance into a repeatable checklist for daily, weekly, and monthly operations.
Daily checks
- [ ] Run
docker context lsand verify the active context is correct for your current work. - [ ] Run
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"(ordocker service lsfor Swarm) to see running workloads. - [ ] Check for unhealthy or restarting containers:
docker ps --filter "health=unhealthy"anddocker service ps --filter "desired-state=running" | grep -v Running(for Swarm). - [ ] Review logs for errors:
docker logs <container> --tail 100ordocker service logs <service> --since 24h.
Weekly maintenance
- [ ] Validate backup integrity for volumes and bind mounts.
- [ ] Test context connectivity from a different machine or user to catch permission issues.
- [ ] Check disk usage:
docker system dfto see if images or containers are bloated. - [ ] Review certificate expiration dates:
openssl x509 -enddate -noout -in cert.pem.
Monthly review
- [ ] Remove unused contexts:
docker context rm <name>after confirming they are not needed. - [ ] Update documentation with any changes in IP addresses, hostnames, or roles.
- [ ] Run a disaster recovery drill: recreate a context from scratch and verify access.
- [ ] Check for Docker Engine updates and test on a staging context before applying to production.
Ownership and cadence
Assign owners for these checks. For example:
- Context management: Priya Shah, DevOps Engineer. Reviews contexts monthly.
- Certificate management: Marcus Chen, Security Lead. Reviews expiry weekly.
- Backup verification: The on-call engineer runs daily backup checks.
- Disaster recovery: Team lead, Carlos Rivera, schedules quarterly drills.
Common Pitfalls and How to Avoid Them
1. Using the default local context for everything
Why it happens: Developers often start with local and add remote hosts but forget to switch contexts. This leads to running commands against your laptop when you meant production.
Avoidance: Create a dedicated context for each environment and set DOCKER_CONTEXT in your shell profile to the correct default for your work. Use a clear naming convention.
2. Storing secrets in context files or scripts
Why it happens: Convenience. Embedding passwords or keys in commands feels faster.
Avoidance: Use SSH keys with passphrase or cert-based auth. Never write secrets in plaintext. Use environment variables or secret managers and reference them in scripts.
3. Not testing context changes before switching
Why it happens: Urgency in production issues leads to quick changes.
Avoidance: Always create a test context, run a read-only command, and only then switch. Keep the old context until you are confident the new one works.
4. Ignoring data persistence in containers
Why it happens: Containers are ephemeral by design, and developers may assume data is automatically persisted.
Avoidance: Explicitly define volumes or bind mounts for all stateful services. Perform a restart test routinely.
5. Not documenting contexts and their endpoints
Why it happens: Contexts are created ad hoc and not recorded.
Avoidance: Maintain a runbook entry for each context with endpoint, authentication method, and purpose. Update it during monthly reviews.
6. Overlooking certificate expiry
Why it happens: Certificates are set and forgotten until they break.
Avoidance: Automate checks with a monitoring tool and set calendar reminders before expiry.
Conclusion
Docker Context production operations are about discipline: observe before changing, keep the blast radius small, protect secrets, verify results, and document recovery paths. This checklist provides a foundation, but every environment is unique. Adapt these steps to your own infrastructure and team workflows.
Start with a low-risk verification today: check your current context, list running containers, and inspect a volume. Then review your context configuration, create a test context, and run through the daily checks. As you gain confidence, integrate the weekly and monthly routines into your team's operations.
A reliable Docker Context setup makes failures visible, protects sensitive values, and limits changes to the intended resource. With this checklist, you can operate your Docker environments with greater safety and confidence.