Tuesday, November 12, 2019

How to SSH from one Docker Container to Other Docker Container


How to SSH from one Docker Container to Other Docker Container

I have tried to deploy the application that is build on one docker and push the final artifact to other docker container and came across the question of how to push to other docker. I searched a little bit and here is how I finally able to ssh to other docker container

Let's say we have two docker containers A and B running in the host environment and I want to do the SSH from docker A to docker B.

Here is the following things that I need in-order to do the SSH to docker B. Make sure both dockers are downloaded and running. Let say I have downloaded the nodejs docker and run as:

$docker run -it --rm -name A -p 50022:22 node /bin/bash
$docker run -it --rm -name B -p 50023:22 node /bin/bash

1. Find the docker container's ip address as below:

$docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' A
$172.17.0.1

$docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'  B
$172.17.0.2

2. Inside the docker container B
$ apt-get update
$ apt-get install ssh

3. Change the following configuration in /etc/ssh/sshd_config file
PasswordAuthentication from 'no' to 'yes'
PermitRootLogin from 'no' to 'yes'

4. Then run the ssh service inside container B as
$service ssh start

5. Change the root password as:
$passwd root
[Enter new password]: _


6. Now from docker container A just do the following:
$ssh root@172.17.0.2
[Enter the password]: _

That's all!


SSH without providing password using ssh keygen

If you want to ssh login without providing password, then following ssh key need to be generated

1. From docker container A, generate rsa key as:
$ssh-keygen -t rsa
the key will be generated by default at ~/.ssh/ folder

2. Upload or transfer the public key id_rsa.pub to container A at the location as given below:
$cat ~/.ssh/id_rsa.pub | ssh root@172.17.0.2 'cat >> ~/.ssh/authorized_keys'

3. It will as one time password to copy, after then
$ ssh root@172.17.0.2
and no password will be asked.

That's all!

Now we can even run the remote script using ssh as:
ssh root@172.17.0.2 << EOF
echo "this is from container B"
pwd
EOF

No comments:

Post a Comment