How to enable SSH within a Docker Container

Muhammad Tabish Khanday
2 min readMar 26, 2021

Prerequisite: This article assumes you have docker installed on your machine.

Step 1: Dockerfile

FROM ubuntu:latestLABEL maintainer="MuhammadTabish" email="mtabishkhanday@gmail.com" version="1.0" location="India" type="ubuntu-ssh"RUN apt update && apt install  openssh-server sudo -yRUN  echo 'root:password' | chpasswdRUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/g' /etc/ssh/sshd_configRUN service ssh startEXPOSE 22CMD ["/usr/sbin/sshd","-D"]

Line 1: Here I am using ubuntu as the base image for the container.

Line 2: We are setting some labels for this Docker Image.

Line 3: By default, Docker does not have sudo installed, hence the need to install it along with the open ssh server.

Line 4: I am setting the password for the root user.

echo 'root:password' | chpasswd sets the password for the root user to password

Line 5: It starts the ssh service

Line 6: It tells docker the container listens on port 22 ( which is the default for ssh)

Line 7: Finally start the ssh daemon.

Step 2: 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 -dit --name [Container Name] -p [PORT]:22 [IMAGE_NAME]

You can check out my docker file here

Finally, you can connect to the container using the user you created, in this case, it will be test so:

ssh test@[ip_address of Docker Host OS] -p [PORT]

enter your password as “password” in the prompt and your all setup.

Finally, our Docker Container is enabled with SSH 🥳

That’s all for today! I’ll be back with some new articles very soon, thanks! 🤗

Muhammad Tabish Khanday

--

--