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 -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 Any connection to on the local machine, will be forwarded to ( is on the remote side), which means you can connect to remote Redis server at 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