Home > Back-end >  How could a docker container access a (mongo-db) service via an ssh tunnel on host
How could a docker container access a (mongo-db) service via an ssh tunnel on host

Time:05-07

I'm trying to connect to a remote mongo-db instance that has restricted access to its local network. So, I create an ssh tunnel, which allows me to connect:

ssh -L [port]:localhost:[hostport] [username]@[remote-ip]

However, when I want to connect to the same mongo-db service from a docker container the connection times out.

I tried to specify a bind address like so

ssh -L 172.17.0.1:[port]:localhost:[host-port] [username]@[remote-ip]

And connect to the remote mongo-db from a docker container at 172.17.0.1:[port], but without success. What's my mistake?

Note: I am looking for a solution that works on both Linux and Mac.

CodePudding user response:

I am suggesting something like this:

version: "3"

services:
  sshproxy:
    image: docker.io/alpine:latest
    restart: on-failure
    volumes:
      - ./id_rsa:/data/id_rsa
    command:
      - sh
      - -c
      - |
        apk add --update openssh
        chmod 700 /data
        exec ssh -N -o StrictHostkeyChecking=no -i /data/id_rsa -g -L 3128:localhost:3128 [email protected]

  client:
    image: docker.io/alpine:latest
    command:
      - sh
      - -c
      - |
        apk add --update curl
        while :; do
          curl -x http://sshproxy:3128 http://worldtimeapi.org/api/timezone/America/New_York
          sleep 5
        done

Here I'm setting up an ssh tunnel that provides access to a remote http proxy, and then in another container I'm accessing that proxy over the ssh tunnel. This is pretty much exactly what you're looking to do with mongodb.

In a real environment, you would probably be using pre-built images, rather than installing packages on-the-fly as I've done in this example.

  • Related