Port forwarding from container to remote server

Hi
I am trying to create a container that uses port forwarding, such that it can (for instance) access a remote database as though it were local.
I tried the following line in my dockerfile as both RUN and CMD
ssh -L 27017:localhost:27017 user@host
but the container exits in all cases (with or without the ‘docker run -d’ flag; it dies also if I add && /bin/bash to the end of the line, as suggested by someone for such cases. I also tried running screen in the dockerfile but this does not seem to be easy to setup, there are tty issues). So to keep the container alive the only solution I have found is to run it interactively and then do the ssh ‘by hand’ in the shell.

Once that’s going, I can open another terminal on my local machine, access the running container using docker exec, and the port forwarding works fine.
Is there some better way to do this? Again I am not trying to get ports on my local host forwarded, rather I want ports in the container
forwarded to a remote server on which my database resides, such that code running in the container sees the remote database.

Hi,

You should consider using -N arguments so that you send the ssh tunnel not to execute any command on the remote node and just to keep the connection open.

Also you should be doing this with the CMD.

eg: ssh -L 27017:localhost:27017 -N -f user@host

Below is a sample Dockerfile

FROM centos:6
RUN yum install -y openssh-clients
COPY id_rsa /tmp/id_rsa
CMD ssh  -i /tmp/id_rsa -L 8000:localhost:8000 -N vagrant@192.168.33.10 -o StrictHostKeyChecking=no

Regards