In this post I will walk you through my process of setting up ssh access to your docker container.
Why run an ssh server within a container in the first place?
The major reason why you might want to do this is for testing purposes, perhaps you are testing infrastructure automation or provisioning with something like ansible which requires ssh access to the target machine, you'd want to test this in a safe environment before going live.
- This article assumes you have docker installed on your machine if not you can refer to this page to get it installed here
The Dockerfile!
FROM ubuntu:latest
RUN apt update && apt install openssh-server sudo -y
RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1000 test
RUN echo 'test:test' | chpasswd
RUN service ssh start
EXPOSE 22
CMD ["/usr/sbin/sshd","-D"]
Here I am using ubuntu as the base image for the container, then on line 2 i install open-ssh server and sudo.
Sudo?
By default docker does not have sudo installed , hence the need to install it along with the open ssh server
On line 3 i create a user called test and add it to the sudo group
echo 'test:test' | chpasswd
sets the password for the user test to test
Line 5 starts the ssh service and line 6 tells docker the container listens on port 22 ( which is the default for ssh) and finally i start the ssh daemon.
Building the image
To build the image run docker build -t IMAGE_NAME .
, once that's done you can run the image using docker run IMAGE_NAME -p 22:22
. finally you can connect to the container using the user you created , in this case it will be test so ssh test@ip_address
enter your password in the prompt and your all setup
The original Dockerfile can be found on my github here
Top comments (12)
Thanks, useful
For those of you who are trying to login with root creds. The user needs to be test and the password is test as well.
After creating the container hit: ssh test@ -p then hit test as the password.
You may also want this line before
RUN service ssh start
Thank you so much!
Thanks!
Thank you so much!
One thing though: I attempted to run
docker run IMAGE_NAME -p 22:22
but it gave me an error. Runningdocker run -p 22:22 IMAGE_NAME
worked instead.Thanks a lot for this post. This helped me in setting up a docker container as a Jenkins build agent in my learning environment.
Is there a way to add public and private key authentication
Thanks! :-)
Thanks for sharing.