Image for post
Image for post

How to enable SSH within a Docker Container

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

Step 1: Dockerfile


FROM ubuntu:latest
LABEL 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] .

Image for post
Image for post

Once that's done you can run the image using:

docker run -dit --name [Container Name] -p [PORT]:22 [IMAGE_NAME]

Image for post
Image for post

You can check out my docker file here

Image for post
Image for post

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]

Image for post
Image for post

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

Image for post
Image for post

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

Lets code 💻.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store