How to spawn a docker container in a remote machine

Viewed 536

Is it possible, using the docker SDK for Python, to launch a container in a remote machine?

import docker
client = docker.from_env()

client.containers.run("bfirsh/reticulate-splines", detach=True)
# I'd like to run this container ^^^ in a machine that I have ssh access to.

Going through the documentation it seems like this type of management is out of scope for said SDK, so searching online I got hints that the kubernetes client for Python could be of help, but don't know where to begin.

3 Answers

It's not clearly documented by Docker SDK for Python, but you can use SSH to connect to Docker daemon by specifying host with ssh://[user]@[host] format, for example:

import docker

# Create a client connecting to Docker daemon via SSH
client = docker.DockerClient(base_url="ssh://username@your_host")

It's also possible to set environment variable DOCKER_HOST=ssh://username@your_host and use the example your provided which use current environment to create client, for example:

import docker
import os

os.environ["DOCKER_HOST"] = "ssh://username@your_host"
# Or use `export DOCKER_HOST=ssh://username@your_host` before running Python

client = docker.from_env()

Note: as specified in the question, this is considering you have SSH access to target host. You can test with

ssh username@your_host

If you have a k8s cluster, you do not need the Python sdk. You only need the cmd line tool kubectl.

Once you have it installed, you can create a deployment that will deploy your image.

Related