Use Docker Contexts for Remote Deployments
Master Docker contexts to manage and deploy your containers across remote Docker hosts seamlessly, enhancing your DevOps workflow.
Focus: Docker contexts remote deployments
You have a local Docker environment working perfectly, but now you need to deploy containers to a remote server, a cloud VM, or even a production cluster. Switching between different hosts, configuring SSH keys, and managing Docker daemon endpoints can introduce friction and security risks. Docker contexts solve this precise pain point: they let you switch between multiple Docker daemon endpoints—local, remote, or cloud—with a single command, keeping your workflow smooth and your deployments consistent.
The problem this lesson solves
Imagine you maintain three Docker hosts: a local development machine, a staging server on AWS, and a production cluster managed by Docker Swarm. Without contexts, you might set environment variables (DOCKER_HOST, DOCKER_TLS_VERIFY), manually copy certificates, or even edit Docker configurations every time you need to run a command on a different host. This approach is error-prone, insecure, and breaks automation.
Docker contexts provide a clean abstraction. A context is a named configuration bundle that includes the host address, TLS certificates, and default namespace for a Docker daemon. Once you create and activate a context, every docker command (like docker ps, docker run, or docker stack deploy) targets that remote daemon without any additional setup. This enables seamless remote deployments, debugging, and management across environments.
Core concept / mental model
Think of Docker contexts as workspace profiles for your Docker client. Each profile stores:
- Endpoint URI: The address of the Docker daemon (e.g.,
tcp://192.168.1.10:2376orssh://user@deploy.example.com). - TLS certificates: Paths to CA, client certificate, and key for encrypted communication.
- Namespace: Optionally, a Kubernetes or Swarm namespace (not the focus here).
💡 Pro tip: Contexts are stored in
~/.docker/contexts/on your local machine. You can inspect them withdocker context ls.
When you issue a command like docker context use remote-staging, your Docker client reads the context's configuration and connects to the specified remote daemon. Commands like docker ps now list containers running on that remote host. To return to local, you simply run docker context use default.
How it works step by step
1. Prerequisites
- Docker CLI installed (version 19.03 or higher).
- A remote Docker host reachable over SSH or TCP (with TLS usually enabled).
- For SSH-based contexts, SSH key-based authentication configured.
2. Creating a context
You can create a context using the docker context create command. For a remote host accessible via SSH:
docker context create remote-staging --description "Staging server SSH" \
--docker "host=ssh://deploy@192.168.1.100"
The SSH URL format is ssh://username@hostname[:port]. The Docker CLI will use your existing SSH key (from ~/.ssh/id_rsa or an agent) to authenticate.
For a TCP connection with TLS (more common in production):
docker context create remote-production --description "Production Docker Swarm" \
--docker "host=tcp://192.168.1.200:2376,ca=/path/to/ca.pem,cert=/path/to/cert.pem,key=/path/to/key.pem"
3. Listing and inspecting contexts
docker context ls
Output:
NAME TYPE DESCRIPTION DOCKER ENDPOINT ERROR
default moby Current DOCKER_HOST based configuration unix:///var/run/docker.sock
remote-staging moby Staging server SSH ssh://deploy@192.168.1.100
remote-production moby Production Docker Swarm tcp://192.168.1.200:2376
Current context is marked with an asterisk.
To inspect a context's details:
docker context inspect remote-staging
4. Switching contexts
Use docker context use <name>:
docker context use remote-staging
Now run a remote command:
docker ps # lists containers on 192.168.1.100
Switch back to local:
docker context use default
Hands-on walkthrough
Let's simulate a real remote deployment. You'll need two terminals: one local, and SSH access to a remote host (or a Vagrant/cloud VM).
Step 1: Prepare remote host
On the remote host, ensure Docker is installed and the daemon exposes port 2375 (or 2376 for TLS). For this lab, we'll use SSH (no TLS setup needed).
Step 2: Create a context for remote
docker context create remote-lab --description "Lab SSH" \
--docker "host=ssh://youruser@remote-ip"
Step 3: Activate the context and deploy
docker context use remote-lab
docker run -d --name nginx-remote -p 8080:80 nginx:alpine
Now open your browser at http://remote-ip:8080 to confirm Nginx runs on the remote host.
Step 4: List remote containers
docker ps
Output shows the Nginx container running on the remote host.
Step 5: Clean up
docker stop nginx-remote && docker rm nginx-remote
Step 6: Return to local context
docker context use default
docker ps # shows local containers again
💡 Blockquote: When you switch contexts, the Docker CLI does not stop any containers—it simply changes which daemon you're talking to. This is safe and non-disruptive.
Compare options / when to choose what
| Approach | Security | Setup complexity | Use case |
|---|---|---|---|
| SSH-based context | Medium (SSH keys) | Low | Development, staging, trusted networks |
| TCP + TLS context | High (certificates) | Medium | Production, multi-tenant clusters |
Environment variables (DOCKER_HOST) |
None | Low but error-prone | Quick testing, no multi-host orchestration |
Docker Compose with host |
Medium | Medium | Single project with a fixed remote target |
When to choose what: - Use SSH contexts for quick remote dev work or when you already have SSH access. - Use TLS contexts for production (third-party CI/CD, cloud providers). - Avoid environment variables if you manage more than one remote host—contexts are more maintainable.
Troubleshooting & edge cases
docker: 'context' is not a docker command.
- Your Docker CLI version is below 19.03. Upgrade Docker Desktop or install a newer Docker CLI.
Permission denied when connecting via SSH
- Check that your SSH key is added to the agent:
ssh-add -l. - On the remote host, ensure your user is in the
dockergroup:usermod -aG docker $USER.
Connection timeout
- Verify the remote daemon is listening:
sudo netstat -tulpn | grep 2376. - Ensure firewalls allow traffic (port 2376 for TCP, 22 for SSH).
- For TLS, double-check certificate paths in the context.
Conflicting DOCKER_HOST environment variable
- If
DOCKER_HOSTis set, the CLI may ignore context. Unset it:unset DOCKER_HOST.
What you learned & what's next
You now understand how to create, inspect, switch, and delete Docker contexts. You can deploy containers to a remote host using SSH or TLS in one command. This skill is foundational for:
- Multi-host Docker Swarm management
- CI/CD pipelines targeting different environments
- Bulk operations across clusters using scripts
- Next lesson: Docker Compose in production – orchestrating multi-service apps on remote hosts with context-aware Compose files.
Mastering contexts means you never have to copy-paste DOCKER_HOST strings again. Your Docker CLI becomes a universal remote control for any cluster.
Practice recap
Create a new Docker context for a remote host using SSH, then deploy a container (nginx:alpine on port 8080) to that host. List the running container via the context. Switch back to default and confirm you see your local containers. Finally, delete the context using docker context rm <name> (you must switch to another context first). Repeat until the workflow feels natural.
Common mistakes
- Forgetting to unset the
DOCKER_HOSTenvironment variable – it overrides the active context and can lead to unintended target selection. - Using an SSH context without having the SSH key loaded in the agent – the connection will fail with a permission error.
- Creating a context with wrong port or protocol (e.g., using
tcp://without TLS when the daemon requires TLS). Always verify the daemon configuration. - Not switching back to the
defaultcontext after remote work – subsequentdockercommands run against the remote host, which might be undesirable or insecure.
Variations
- Use
docker context exportandimportto share contexts across team members or CI environments. - Use context with Kubernetes by setting
--default-stack-orchestrator=kubernetesduring creation. - Combine contexts with shell aliases (
alias prod='docker context use production') for fast switching.
Real-world use cases
- Deploying microservices to a staging server on AWS via SSH from a CI/CD pipeline without exposing Docker daemon ports.
- Managing a Docker Swarm cluster in production with TLS contexts to securely run
docker stack deployfrom any admin workstation. - A developer switching between local development, a shared dev server, and a remote GPU-enabled host for ML workloads using simple context commands.
Key takeaways
- Docker contexts are named configurations that map your Docker CLI to a specific Docker daemon endpoint.
- Create a context with
docker context createusing SSH or TLS endpoints. - Switch active context with
docker context use <name>– this affects all subsequentdockercommands. - Use SSH contexts for convenience in dev/staging, and TLS contexts for production security.
- Always verify the active context with
docker context lsbefore running destructive commands (remove, stop, prune). - Unset
DOCKER_HOSTenvironment variable to avoid conflicts with context-based connections.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.