I want to create a network of a container in which one central container should be able to ssh into all other containers. Through ssh central container can change a configuration of all other container using Ansible. I know that it’s not advised to ssh from one container to another, and we can use volume for data sharing but that doesn't fit to my use case. I am able to ssh from host to the container but I am not able to ssh from one container to another.
Docker file I am using is:
FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install -y netcat ssh iputils-ping
EXPOSE 22
Image created by the Dockerfile is named ubuntu:v2
Then using below commands I created two containers u1 and u2
docker run -p 22 --rm -ti --name u1 ubuntu:v2 bash
docker run -p 22 --rm -ti --name u2 ubuntu:v2 bash
In the container I am running below commands to create a user in container. Create user u1 in u1 container and u2 in u2 container
root@d0b0e44f7517:/# mkdir /var/run/sshd
root@d0b0e44f7517:/# chmod 0755 /var/run/sshd
root@d0b0e44f7517:/# /usr/sbin/sshd
root@d0b0e44f7517:/#
root@d0b0e44f7517:/# useradd --create-home --shell /bin/bash --groups sudo u2
root@d0b0e44f7517:/# passwd u2
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
root@d0b0e44f7517:/#
root@d0b0e44f7517:/#
I made two containers, both are same except one has user u1 and other has user u2 as shown above. After this, I tried to ssh from host to container using command ssh -X u2@localhost -p 32773 (32773 is a port which is mapped to container’s 22 port). So ssh works from host to container but I am not able to ssh from one container to another container.So can you help me to ssh from one container to other containers?
Use docker service discovery and then you can ssh from one container to another container. Here you can achieve service discovery by connecting all the containers to the same network.
docker network create -d bridge test
docker run -p 22 --rm -ti --name u1 --network test ubuntu:v2 bash
docker run -p 22 --rm -ti --name u2 --network test ubuntu:v2 bash
Now from u1
you can ssh into u2
as ssh user@u2
.
docker exec -it u1 /bin/bash
docker exec -it u2 /bin/bash
passwd #Change the password of container it will be asked during ssh
apt-get update
apt-get install vim
apt-get install openssh-client openssh-server
vi /etc/ssh/sshd_config
service ssh restart
Now you can ssh using root@container_ip
to any container
Note: to get container ip you can run the below command
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <conatiner_name>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With