How to SSH and Expose your container using Dockerfile in 3 STEPS.

In this blog post, you will learn why and how to set up an SSH-server in a docker container and expose its port.

How to SSH and Expose your container using Dockerfile in 3 STEPS.

Prerequisites

  • Linux environment integrated with Docker

Use cases

  • SSH is mainly used to connect to a container.

  • Testing purposes: To test or update files inside a container.

  • Remote development in the container.

Lets Begin!

1. Creating Dockerfile

Command to create dockerfile in vim editor

vi Dockerfile

Here's my dockerfile

FROM ubuntu:latest

RUN apt update

RUN apt install  openssh-server sudo -y

RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1000 divyam

RUN service ssh start

RUN  echo 'divyam:123' | chpasswd

EXPOSE 22

CMD ["/usr/sbin/sshd","-D"]

Breaking down the file

Line 1: Using Ubuntu as the base image for my container and choosing the latest version

Line 2,3: updating & installing ssh-server and sudo

Line 4: Adding user divyam into sudo group. The command creates a home folder for the new docker user and bash is shell by default

Line 5: Starting the ssh service

Line 6: sets the password for user divyam to 123

Line 7: Exposing port 22 of the container which will be available for requests

Line 8: The CMD command​ specifies the instruction that is to be executed when a Docker container starts here we are starting the ssh daemon in the background.

The shortcut to save the docker file - Press escape then :wq and Enter

Your dockerfile is ready to be built now!

2. Building Dockerfile and running the container.

// Building image from the dockerfile lying in the current directory, you may need to specify directory path if your dockerfile is not in the current directory
docker image build -t myubuntu:051 .
// Running the container in the background on port 80 of my machine 
docker container run -p 80:22 -d myubuntu:051
// check the running container 
docker container ls

image.png

Congrats! your container is running successfully on port 80 and the command is the same as given in CMD.

Note: I made a mistake of using the port command at the end which cost me a lot of time make sure to not do this docker container run -d myubuntu:051 -p 80:22

3. SSHing the container

For doing SSH into your container you will need IP of your machine. I used ifconfig command to find the IP.

image.png

Command to SSH

// ssh user@IP -p (portnumber)
ssh divyam@172.22.175.127 -p 80

// enter the password

You are into the container now! perform cat command to check the os-release version

image.png

Conclusion

There's a lot of debate around the best methods for getting a shell inside a container like exec, attach commands. Will be covering those topics in my next blogs. I hope you found this article useful.

Let's connect on Social media Twitter and Linkedin

👋 Thanks for reading this article, share and follow if you liked this and stay tuned for more!