Control remote containers with Docker contexts over SSH

Leverage great tools to ease operations

Geschrieben von Timo Rieber am 12. April 2025

When working with remote servers, SSH is the go-to protocol. But constantly connecting to machines to run Docker commands there gets tedious. Docker contexts let you switch between local and remote Docker daemons seamlessly.

Here’s how to set up a Docker context over SSH and run a simple container remotely.

Prerequisites

Ensure you can SSH into the remote host without a password using SSH keys. You also need Docker installed locally and on the remote server.

Create a new Docker context using SSH

First, we're creating a Docker context with SSH. Replace

docker context create <context-name> \
  --docker "host=ssh://<user>@<your.remote.host>"
Bash

Use your new context

There are different ways to use a context. One is to activate the remote context until you switch it again:

docker context use <context-name>
docker context ls
Bash

Another common way is to use it in every command explicitly. This is more flexible, but every command needs to carry the context parameter:

docker --context <context-name> context ls
Bash

Execute Docker commands on the remote host

For the rest of this article we're going with the activated context. Let's see, what Docker containers are running:

docker context use <context-name>
docker ps
Bash

Or let's start a vanilla NGINX server:

docker run \
  --rm --detach \
  --name nginx-test \
  --publish 8080:80 \
  nginx
Bash

The container is now running on the remote server, accessible via http://<your.remote.host>:8080.

You can issue every command as you would with a local container. Often you need to open a shell inside the container:

docker exec --tty --interactive nginx-test bash
Bash

Try ls or env to verify. That's all for now, so exit the interactive shell with CTRL+D and stop the container. It gets automatically removed, because of the --rm flag we used in the run command above:

docker stop nginx-test
Bash

Don't forget to switch back to your local Docker context with docker context use default.

Summary

Docker contexts are a clean way to manage multiple environments, especially remote ones. Once set up, it's as easy as flipping a switch. They can also be shared with others using the docker context export and docker context import commands.

In practice, I’ve used this for:

  • Managing test and production environments on remote hosts
  • Debugging production issues
  • Automating remote builds and deployments