How to SSH into a Docker Container | Step-by-Step Tutorial

October 17th, 2023
How to SSH into a Docker Container | Step-by-Step Tutorial

SSH access proves invaluable when it comes to debugging and troubleshooting Docker containers. Its importance lies in how easy it is to gain access to the container's shell. This article will show you how to SSH into a Docker container, including setting up a Docker container for SSH security access, as well as authorizing an SSH connection through the preprogrammed port.

What is SSH?

The Secure Shell Protocol (SSH) is a secure network protocol to perform encryption, authentication, and command execution between devices securely over unsecured networks.

What is SSH access?

SSH access refers to using Secure Shell (SSH) to connect to a remote server or device to interact with remote systems in a secure and encrypted manner. SSH access into Docker containers grants numerous advantages, including the capability to execute commands on a remote server, access files within the container's file system, and establish crucial connections for debugging tasks.

Prerequisites

Make sure you have the following requirements before we begin.

  • A Linux-based host system with Docker installed
  • The fundamentals of Docker and a basic idea of how to use the command-line interface.

Once the prerequisites are met, you can get started with the step-by-step guide to SSH into a Docker container.

Ready to supercharge your Docker infrastructure? Scale effortlessly and enjoy flexible storage with Cherry Servers bare metal or virtual servers. Eliminate infrastructure headaches with free 24/7 technical support, pay-as-you-go pricing, and global availability.

SSH into Docker container: Step-by-step process

With Docker's ease of use and isolation of resources, SSH access to a container's shell can provide a simple way for tasks like debugging and troubleshooting applications. Follow the below four steps to SSH into Docker container.

Step 1: Create a Dockerfile

To build a customized Docker image with SSH server enabled, let’s start by creating a Docker file.

1. Set up the working environment

Make a new directory with the files related to the customized Docker image. In the example below, we have named the directory as "my_ssh_image". You have to enter the following commands in the terminal in order to create the directory.

mkdir my_ssh_image

make directory

Execute the following command to navigate to the directory.

cd my_ssh_image

navigate to directory

2. Create the Dockerfile

You can easily create the Dockerfile using a text editor of your choice such as Nano or Vim.

nano Dockerfile

Create docker file

Copy and paste the below code sample on the Dockerfile.

FROM ubuntu:16.04
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
# Set root password for SSH access (change 'your_password' to your desired password)
RUN echo 'root:your_password' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

Some of the meanings of the syntaxes in the code above are mentioned below.

  • FROM ubuntu:16.04 changes the standard Ubuntu 16.04 image that can be found on Docker Hub as the base image for our custom Docker image. The instructions that follow will be constructed on top of this base image.
  • The RUN apt-get update && apt-get install -y openssh-server command updates the package index within the container and installs the OpenSSH-server package, which is required for the SSH server functionality.
  • RUN mkdir /var/run/sshd is used to set up a directory /var/run/sshd inside the container. The SSH daemon requires this directory to function.
  • RUN echo 'root:your_password' | chpasswd sets the root user's password inside the container. Replace 'your_password' with your desired password.
  • RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config” changes the sshd_config file to enable root password login, which means allowing the "root" user to log in using a password instead of relying on other authentication methods like SSH keys.
  • RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd modifies the Pluggable Authentication Module configuration for the SSH daemon to prevent possible issues with systemd.
  • EXPOSE 22 exposes port 22 in the container, allowing SSH connections to the SSH server running inside the container.
  • CMD ["/usr/sbin/sshd", "-D"] specifies the default command to run when a container is started from this image. In this case, it starts the SSH daemon in the foreground with the -D option, allowing the container to keep running as long as the SSH server is active.

code for docker file

Press ctrl+x and press y and then press Enter to save the file.

Step 2: Build custom Docker image

Next, let’s build the custom Docker image using Dockerfile.

1. Navigate to the Dockerfile directory

We are already in the Dockerfile directory. If not, you can use the below command to navigate to the Dockerfile directory. Afterward, build the Docker image with a tag.

cd <path to directory>

Run the following command by including the tag (e.g.: my_ssh_image)

sudo docker build -t my_ssh_image .

building docker image

2. Inspect the created image

Run the below command to inspect the created image.

sudo docker images

inspect the created image

Step 3: Run the Docker container with SSH access

We'll run an SSH server in a container to allow SSH access to the Docker container. To make it easier to identify the container, we'll map the SSH port between the host and the container in this step.

1. Map the SSH port between the host and container and name the container

The following command creates a Docker container with SSH server enabled, mapping host port 2222 to container port 22 and setting the name of the container to "my_ssh_container".

sudo docker run -d -p 2222:22 --name my_ssh_container my_ssh_image

Map the SSH port

2. Verify SSH connectivity between the Docker host and the container

Run the command shown below to check SSH connectivity between the container and the Docker host. The port mappings or a specific mapping for the container are listed via the Docker port command,

sudo docker port my_ssh_container

Verify SSH connectivity

Step 4: SSH into Docker container

Now, you can start performing tasks inside the Docker container. In this step, we'll show you how to connect through SSH into a Docker container so you may interact with it directly.

Explore how web hosting service provider Debesis improved its service quality, performance, and reliability by migrating to Cherry Servers' bare-metal servers.

"Cherry Servers engineers always help when we need them, while their customer service quality is a blast!"

1. Find the IP address of the container

Next, discover the container's IP address. You can run the Docker inspect command to accomplish that.

sudo Docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my_ssh_container

Find the IP Address

2. Use the SSH command to SSH into the container

Replace <your_IP_address> with the received IP address from the previous command.

ssh root@<your_IP_address>

Use SSH command

Next, enter the password you used to set up the Docker file in Step 1.

3. Successfully log in and access the container's shell

Successfull login

You can now run any commands you like.

Example commands

uname -a

The uname -a command displays system information in UNIX-like operating systems. It provides details such as the kernel name, hostname, kernel release date, and processor type.

uname-a command

free -h

The free -h command shows the total used and free space of physical memory (RAM) and swap memory in a human-readable format.

free-h command

Finally, type exit to end the session and log out after you finish executing tasks.

exit

exit command

Conclusion

Granting SSH access to Docker containers is important for communicating with the container shell. Here, you have learned how to create a unique Docker image with an SSH server enabled, run a container with SSH access, and safely connect to it using SSH.

After getting access, you can execute commands, access files, and troubleshoot issues in the container environment. SSH access to Docker containers can improve productivity and make container management simpler.

Run your Docker containers in a scalable and high-performing open cloud environment with Cherry Servers bare metal cloud tailored for containerized workloads: automatic scaling, pay-as-you-go pricing, and free 24/7 technical support for complete control.

Shanika is a technical consultant and writer with over eight years of experience as a software engineer in the IT sector. Her professional journey started as a software engineer with WSO2. At the same time, she started working as a freelancer on Upwork. She has collaborated with numerous companies throughout her freelance career, including Digication, Splunk, BMC.com, Filestack, APILayer, Flosum, Blazemeter, Sencha, and over twenty others. Having opportunities to work with various companies in different roles has allowed her to amass a wealth of experience. Shanika is an expert in web development, programming, Java, Python, React, Cypress, CI/CD, Docker, and Kubernetes,m. She has significantly contributed to developing products such as IAM solutions, APIs, OCR technologies, test management systems, and front-end frameworks throughout her career. She has also produced blog articles, tutorials, user guides, product documentation, and many other documents, as well as consulting companies to enhance their productivity. Overall, Shanika brings together the experience of a web developer, automation engineer, DevOps developer, software consultant, and technical writer, which is the main reason behind her success as a freelancer. Shanika received her B.Sc. (Hons) in Computer Science from University of Moratuwa, Sri Lanka and resides in Colombo, Sri Lanka.

Start Building Now

Deploy your new Cloud VPS server in 3 minutes starting from $5.83 / month.

We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 00704c37.693