How to Use Docker Context: Manage Multiple Docker Environments
Use
docker context commands to create, list, and switch between different Docker environments. This lets you manage multiple Docker hosts or clusters by selecting the active context with docker context use <context-name>.Syntax
The docker context command manages Docker contexts. Key subcommands include:
docker context ls: Lists all available contexts.docker context create <name> --docker <options>: Creates a new context with Docker endpoint options.docker context use <name>: Switches the active context to the specified one.docker context inspect <name>: Shows details of a context.docker context rm <name>: Removes a context.
Each context stores connection info to a Docker host or cluster.
bash
docker context ls
docker context create myremote --docker "host=ssh://user@remote-host"
docker context use myremote
docker context inspect myremote
docker context rm myremoteExample
This example shows how to create a new Docker context for a remote host accessed via SSH, switch to it, and verify the active context.
bash
docker context create remote-ssh --docker "host=ssh://user@192.168.1.100"
docker context use remote-ssh
docker context lsOutput
NAME DESCRIPTION DOCKER ENDPOINT KUBERNETES ENDPOINT ORCHESTRATOR
default * Current DOCKER_HOST based configuration unix:///var/run/docker.sock
remote-ssh - ssh://user@192.168.1.100
Common Pitfalls
Common mistakes when using Docker contexts include:
- Trying to use a context that does not exist, causing errors.
- Not switching back to the
defaultcontext after using a remote one, which can confuse local Docker commands. - Incorrectly specifying the Docker host URL when creating a context, leading to connection failures.
Always verify the active context with docker context ls and ensure the host URL is correct.
bash
docker context use non-existent-context
# Error: No such context: non-existent-context
docker context use default
# Switches back to local DockerOutput
Error: No such context: non-existent-context
Quick Reference
| Command | Description |
|---|---|
| docker context ls | List all Docker contexts |
| docker context create | Create a new context with Docker host URL |
| docker context use | Switch to a specified context |
| docker context inspect | Show details of a context |
| docker context rm | Remove a context |
Key Takeaways
Docker contexts let you switch easily between multiple Docker environments.
Use 'docker context create' to add new environments with connection details.
Always check the active context with 'docker context ls' before running commands.
Switch back to the 'default' context to use your local Docker engine.
Incorrect host URLs or missing contexts cause connection errors.