Can we SSH into a Docker Container ?

Rahulbhatia1998
4 min readNov 17, 2022

Docker is a utility that lets you create a container for running Applications. A Docker Container is a fully-contained virtual machine.

This blog will show you how we can use SSH to connect to a Docker container and run commands.

You can connect to a Docker container using SSH (Secure Shell). Normally, SSH is used to connect remotely over a network to a server. The technology works the same when connecting to a virtual Docker container on you system.

Let’s start doing this.

For this demo, I’m Using RHEL-8 as my base OS

Step 1: Setting the firewall rules in my Base OS Redhat.

As we are going to give external port to our docker container so we have to set the firewall rule for that port.

Masquerading allows for docker ingress and egress. And in the same way we can allow specifically incoming traffic on port 81 which is going to be my external docker port for ssh. And at last reloading the firewall will apply permanent rules for allowing traffic.

Step 2: Starting the docker

If it is allready started do restart it.

Step 3: Launching a new Docker container

Now we are going to create a new Docker container and in my case I am giving ssh_server name and giving the external port 81. So if any traffic comes here we are going to have traffic for SSH on port 22, from the outside world it will be redirected to this Docker container.

Step 4: Configuring the SSH Server

Whenever we want to access a VM/laptop from other system remotely in that VM we have to Configure a Program or configure that system as a server & this program is Remote Program Execution Server or SSH Server. Here are going to configure the SSH server in our docker container named ssh_server.

For configuring ssh Server this are the following steps:-

1. Install the SSH softwares/Packages

2. Setting the password for the root for the Container

3. Start the SSH Service

Here we will not able to start the services as we can clearly see we have to load the SSH keys first.

Now SSH is configured for this ssh_server docker container and now it is ready to connect remotely through SSH.

We can do SSH firstly from another Docker Container and secondly from the windows using Putty. Let’s connect from both ways….

Remotly login from another Docker contanier

Step 1: Install the openssh-clients software

Here I am launching a new container named ssh_client with centos latest image.

Step 2: Do SSH to the ssh_server docker container

Now we had login to the docker container named ssh_server.

Remotly login from Putty

Here we have to login with the base OS IP in the Host name block and give the docker external port 81 in the Port Block.

Thus, we have connected remotely using SSH.

--

--