Search code examples
pythondockerssh-tunnel

reach docker over remote using SSHTunnelForwarder


Im still new to docker and im trying to do somthing like this:

from sshtunnel import  SSHTunnelForwarder    
import docker

server = SSHTunnelForwarder(
    'didi',
    ssh_username="george",
    ssh_password="ice",
    remote_bind_address=('192.168.56.103',22),
    local_bind_address =('unix:///var/run/docker.sock')
)

server.start()    
print(server.local_bind_port)    
client = docker.from_env()   
server.stop()

im getting the ValueError: Platform does not support UNIX domain sockets. and at the same time i didnt find a "secure" way to let the docker listen on a local port.

Does anyone know a simple workaround to resolve this? Thanx


Solution

  • If you are trying to reach Docker on a remote machine, you would need to forward a port on your local machine to the Docker socket on the remote machine. You can do this using an ssh command line like this:

    ssh -L 4321:/var/run/docker.sock 192.168.56.103
    

    As long as that connection is active, you can access Docker on local port 4321:

    docker -H tcp://localhost:4321 ps
    

    Unfortunately, the sshtunnel package does not support forwarding access to a remote Unix socket like this (see the api documentation for the local_bind_address and remote_bind_address options).

    But you're in luck! You don't need to manually set up this sort of port forwarding; Docker is able to connect to a remote host via ssh all by itself by setting your DOCKER_HOST environment variable to an ssh url:

    $ export DOCKER_HOST=ssh://192.168.56.103
    $ python
    Python 3.9.0 (default, Oct  6 2020, 00:00:00)
    [GCC 10.2.1 20200826 (Red Hat 10.2.1-3)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> c = docker.from_env()
    >>> info = c.info()
    >>> info['ServerVersion']
    '19.03.13'