Connect to Redis via SSH port forwarding

From inside a Docker container, I need to connect to the Redis server that started on another Amazon EC2 instance.

For safety and temporary use reasons, I chose to use the SSH port forwarding:

ssh -f -L 172.17.0.1:6379:127.0.0.1:6379 -N user@remote
  • -L options for local port forwarding.
  • -f option: let ssh run in the background.
  • -N option: do not to execute a remote command.

The default gateway of Docker is 172.17.0.1. Any connection to 172.17.0.1:6379 on the local machine, will be forwarded to 127.0.0.1:6379 (127.0.0.1 is on the remote side), which means you can connect to remote Redis server at 172.17.0.1 port 6379.

You can check the connection with:

lsof -i:6379 -P | grep -i listen

Use --add-host flag to add a host to IP mapping inside the container, so that you can connect Redis via host.docker.internal:6379.

docker run --add-host=host.docker.internal:host-gateway -d -it --name <container> <image>

And if you want to use redis-cli to connect to Redis server outside of the container environment, specify the -h option:

$ redis-cli -h 172.17.0.1