How to SSH tunnel to a Docker container on a remote server

-

Docker makes it easy to ensure that your project has all of the dependencies that it needs. It makes sense to run your web server within a Docker container, but you might want to access the web server via your browser (i.e., map a port on your machine to a port within the Docker container). Moreover, you might want to run the web server within a Docker container on a remote server, and map a port on your local machine to the web server. This tutorial explains how you can do so easily.

1) Expose the port within your Docker container to the remote server

First, SSH into your remote server. Then, find the image of the Docker container that you want to launch with docker images.

Now, run the image, exposing the port that you want to eventually forward to. For example, if I wanted to map to port 8080 within the Docker container, I would run:

docker run -it --expose 8080 -p 127.0.0.1:8080:8080 {NAME_OF_IMAGE}

which exposes port 8080 of the Docker container. See the documentation.

If your web server starts as soon as the Docker container is started, then you should be done with this step. That is, you should be able to run wget 127.0.0.1:8080 from the server and access the web server within the Docker container. If your web server doesn't start immediately, you can enter the container (docker exec -it {CONTAINER_NAME} bash) and start the web server.

2) Port-forward from your local machine to the remote server

Now you just need to map a port on your local machine to the appropriate port on the server. Going along with the previous example (port 8080), we could run:

ssh -NL 8080:localhost:8080 {REMOTE_SERVER_IP}

which would forward port 8080 on my local machine to port 8080 on the server. Now you should be able to navigate to http://localhost:8080 and access the web server within the Docker container.

Let me know if you run into any difficulties!

Further reading: Can you run GUI apps in a Docker container? (Stack Overflow)

Tags: docker ssh tunnel port forward forwarding container

See also: Three Controversial Beliefs About Living Things

Back to all posts

Neel Somani

About the Author

I'm the founder of Eclipse. You can follow me on Twitter.