DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How to setup an ssh server within a docker container
s1ntaxe770r
s1ntaxe770r

Posted on • Updated on

How to setup an ssh server within a docker container

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"]

Enter fullscreen mode Exit fullscreen mode

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 (7)

Collapse
 
driftuazartur profile image
driftuazartur

Thanks, useful

Collapse
 
davidkassa profile image
David Kassa

Thank you so much!

Collapse
 
tandavala profile image
Jose Tandavala

Thanks!

Collapse
 
bhavaniravi profile image
Bhavani Ravi

Is there a way to add public and private key authentication

Collapse
 
jmielbrechtsymetrix profile image
Jordan Mielbrecht

Thank you so much!

One thing though: I attempted to run docker run IMAGE_NAME -p 22:22 but it gave me an error. Running docker run -p 22:22 IMAGE_NAME worked instead.

Collapse
 
artemgrachov profile image
Artem Grachov

Thanks! :-)

Collapse
 
cheloneffa profile image
Marcelo Neffa

Thanks ! I was just looking for this configuration. It works fine

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.