How to SSH into Docker? How to SSH into Docker? docker docker

How to SSH into Docker?


Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed.Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>. i.e:

docker run -p 52022:22 container1 docker run -p 53022:22 container2

Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>. I.e.:

ssh -p 52022 myuser@RemoteServer --> SSH to container1

ssh -p 53022 myuser@RemoteServer --> SSH to container2


Notice: this answer promotes a tool I've written.

The selected answer here suggests to install an SSH server into every image. Conceptually this is not the right approach (https://docs.docker.com/articles/dockerfile_best-practices/).

I've created a containerized SSH server that you can 'stick' to any running container. This way you can create compositions with every container. The only requirement is that the container has bash.

The following example would start an SSH server exposed on port 2222 of the local machine.

$ docker run -d -p 2222:22 \  -v /var/run/docker.sock:/var/run/docker.sock \  -e CONTAINER=my-container -e AUTH_MECHANISM=noAuth \  jeroenpeeters/docker-ssh$ ssh -p 2222 localhost

For more pointers and documentation see: https://github.com/jeroenpeeters/docker-ssh

Not only does this defeat the idea of one process per container, it is also a cumbersome approach when using images from the Docker Hub since they often don't (and shouldn't) contain an SSH server.


These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)

Dockerfile

FROM swiftdocker/swiftMAINTAINER NobodyRUN apt-get update && apt-get -y install openssh-server supervisorRUN mkdir /var/run/sshdRUN echo 'root:password' | chpasswdRUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config# SSH login fix. Otherwise user is kicked off after loginRUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshdENV NOTVISIBLE "in users profile"RUN echo "export VISIBLE=now" >> /etc/profileCOPY supervisord.conf /etc/supervisor/conf.d/supervisord.confEXPOSE 22CMD ["/usr/bin/supervisord"]

supervisord.conf

[supervisord]nodaemon=true[program:sshd]command=/usr/sbin/sshd -D

to build / run start daemon / jump into shell.

docker build -t swift3-ssh .  docker run -p 2222:22 -i -t swift3-sshdocker ps # find container iddocker exec -i -t <containerid> /bin/bash

enter image description here