Search code examples
dockerdocker-composedockerfilemqtt

SSH Tunnel within docker container


I have a client running in a docker container that subscribes to a MQTT broker and then writes the data into a database. To connect to the MQTT Broker i will have to set up port forwarding.

While developing the client on my local machine the following worked fine:

SSH -L <mqtt-port:1883>:localhost:<9000> <user>@<ip-of-server-running-broker>

The client is then configured to subscribe to the MQTT broker via localhost:9000. This all works fine on my local machine.

Within the container it wont, unless I run the container with --net=host but I'd rather not do that due to security concerns.

I tried the following:

  1. Create docker network "testNetwork"
  2. Run a ssh_tunnel container within "testNetwork" and implement port forwarding inside this container.
  3. Run the database_client container within "testNetwork" and subscribe to the mqtt broker via the bridge network like ("ssh_tunnel.testNetwork:")

(I want 2 seperate containers for this because the ip address will have to be altered quite often and I don't want to re-build the client container all the time)

But all of my attempts have failed so far. The forwarding seems to work (I can access the shell on the server in the ssh container) but I haven't found a way to actually subscribe to the mqtt broker from within the client container.

Maybe this is actually quite simple and I just don't see how it works, but I've been stuck on this problem for hours by now... Any help or hints are appreciated!


Solution

  • The solution was actually quite simple and works without using -net=host. I needed to bind to 0.0.0.0 and use the Gateway Forwarding Option to allow remote hosts (the database client) to connect to the forwarded ports.

    ssh -g -L *:<hostport>:localhost:<mqtt-port/remote port> <user>@<remote-ip>

    Other containers within the same Docker bridge network can then simply use the connection string <name-of-ssh-container>:<hostport>.