SSH to Docker Host from Docker Container: A Quick Guide
Hello fellow developers! 👋 While most guides show you how to SSH into a Docker container from the Docker host, today we’re flipping the script. In this article, we will discover how to establish SSH connections from a Docker container to the Docker host.
The steps are pretty simple:
- Install OpenSSH Server on the Docker host
- Start a Docker container and install OpenSSH Client on it
- SSH from the Docker container to the Docker host with the hostname
host.docker.internal
(Docker Desktop) or the host IP172.17.0.1
(Docker Linux)
If you’re using Docker Desktop version 18.03 onwards, connecting to the special DNS name host.docker.internal
will resolve the internal IP address used by the host. For Docker on Linux, the IP address of the Docker host is always 172.17.0.1
when using default networking.
I’m using Docker Desktop and WSL2, but this should work fine on Mac as well.
Install the OpenSSH server on the Docker host
To install the OpenSSH Server in Ubuntu/Debian Linux, you need to execute the following command.
sudo apt update
sudo apt install openssh-server
Start the SSH service.
sudo service ssh start
Check the status of the SSH service.
sudo service ssh status
To verify if the SSH service is functioning correctly, you can SSH into localhost using your current username and password. Use the following command in your terminal:
ssh YOUR_USERNAME@localhost
Start A Docker Container
We will use Ubuntu here, let’s run the container by executing the following command.
docker run -it --name my-ubuntu --hostname my-ubuntu ubuntu bash
SSH to Docker host from the container
We need to install the OpenSSH Client in the container first. Execute the following command.
apt update
apt install openssh-client
Now we can establish SSH connections from a Docker container to the Docker host. If you are using Docker Desktop, connect to host.docker.internal
.
ssh DOCKER_HOST_USERNAME@host.docker.internal
If you are using Docker for Linux, connect to 172.17.0.1
.
ssh DOCKER_HOST_USERNAME@172.17.0.1
Congratulation! You make an SSH connection from a Docker container to the Docker host. 🎉
Remember to exercise caution when allowing SSH access from a Docker container to the Docker host. Ensure that you have proper security measures in place to protect your systems and data.