Difficulty: Advanced
What is a Docker context, and how do you use contexts to manage local and remote Docker hosts?
A Docker context is a named profile that tells the Docker CLI which daemon to talk to and how to authenticate, for example your laptop's local socket, a staging VM over SSH, or a production host over TLS. You switch with docker context use <name>, and every later docker and docker compose command runs against that daemon without changing any flags.
Each context holds an endpoint (host=unix:///var/run/docker.sock, host=ssh://user@server, or host=tcp://server:2376 plus TLS certificates) and an optional description. They live under ~/.docker/contexts/, and docker context ls shows them with an asterisk on the current one. Docker Desktop creates contexts like desktop-linux automatically.
The order of precedence, highest first:
--context <name> (or -c) flag on a single command.DOCKER_HOST environment variable, which overrides any context.DOCKER_CONTEXT environment variable.docker context use.This precedence is a common source of "why is my command hitting the wrong server" bugs. If DOCKER_HOST is exported in your shell profile, switching contexts appears to do nothing.
docker compose up -d from your laptop; the Compose file is read locally, but containers start on the remote host.dev, staging and prod contexts with clear names is safer than juggling IP addresses.-v ./config:/app/config mounts the server's ./config, not your laptop's. Use volumes or copy files into the image.ssh://), which reuses your keys and needs no open Docker port, or TCP on 2376 with mutual TLS.docker group (or using rootless Docker).--context prod explicitly for prod commands.docker context create ecs and aci integrations from the Compose CLI were retired in 2023; current contexts are Docker endpoints only.# Remote host over SSH (uses your ~/.ssh keys)
docker context create staging \
--description "Staging VM in ap-south-1" \
--docker "host=ssh://deploy@203.0.113.10"
docker context ls
# Switch for all following commands
docker context use staging
docker compose up -d
# One-off command against another context
docker --context default ps
# Back to local
docker context use default
SSH contexts need no exposed Docker port. `--context` runs a single command elsewhere without changing the active context.
docker context create prod \
--docker "host=tcp://prod.example.internal:2376,ca=$HOME/certs/ca.pem,cert=$HOME/certs/cert.pem,key=$HOME/certs/key.pem"
# Check what a context points to
docker context inspect prod --format '{{.Endpoints.docker.Host}}'
Port 2376 with mutual TLS is the secure TCP option; never expose an unauthenticated daemon on 2375.
docker context, DOCKER_HOST, SSH Endpoint, Remote Daemon, TLS