
How to enable SSH within a Docker Container
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 -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"]
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 created a user called test and added it to the sudo group
echo 'test:test' | chpasswd
sets the password for the user test to test
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 “test” 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