Use a host SSH tunnel from a container


I have a home server (Ubuntu 20.04, LXD 4) and an external server with MongoDB (port 27017).
I added a container and set a static IPv4.
I added an autossh tunnel from the host (home server) to the external server.

Now, my question is: how a program inside the container can use the tunnel ?

I try a connection with the ip of the host (, but it’s refused.

The idea of putting the tunnel in the host, instead of the container, is, if I add another container, this new container has automatically access to MongoDB. (but maybe isn’t a good idea :blush: )

If you create a tunnel with SSH, you use localhost:forwarded_port and SSH will forward the traffic to the other end of the tunnel, as you’ve configured it in the SSH command.

For instance, to forward TCP port 2222 to the same port on the server, you’d run something like this:
ssh -L2222:localhost:2222 user@server

…then connect to localhost:2222.

Thanks for your response Aaeron.

But the problem is not the tunnel, it works well.
The problem is using the host tunnel from the container.

I don’t think SSH tunnels are meant for use outside localhost, and even though the container is kinda localhost I don’t believe it will work without further configuration. Have you tried using iptables to redirect traffic on the host? Maybe something that will REDIRECT or DNAT incoming traffic on to localhost:27017?

Sorry for the late response.
I’m not sure that is possible. And I’m very bad with ipatbles.
After some tests, I stopped. I install MongoDB in a container locally :slight_smile:
Thanks for help !

1 Like