Docs
Adding SSH support to an image

Adding SSH support to an image

Adding SSH support to an image that doesn't support it is possible.

Ensure Docker is correctly installed in your environment. If the base image requiring SSH support is in a private registry, authenticate with that registry.

Create a new folder for your Docker project. Inside this folder, create a Dockerfile. We will use this file to extend the base image with SSH support.

Here is an example. You will need to make the necessary modifications to your own image.

# Use your base image
FROM your/base-image
 
# Install OpenSSH and necessary utilities
 
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
 
# Default SSH configuration
 
# Disable password authentication by default; it can be enabled via an environment variable
 
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN echo "PasswordAuthentication no" >> /etc/ssh/sshd_config
 
# Script to set up user, password, or SSH key, and configure password authentication
 
COPY setup-ssh.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/setup-ssh.sh
 
# Expose the SSH port
 
EXPOSE 22
 
# Command to run the setup script and start the SSH server
 
CMD ["/usr/local/bin/setup-ssh.sh"]
 

Make sure you add the setup-ssh.sh file in the same location of the Dockerfile.

This script defines the following environment variables that you can use during deployment.

Variable nameValueDescription
SSH_USERstring(Optional) Defines the user who will be logged in. Default value is root.
PUBLIC_KEYstringString of your public SSH key.

The script is set to run as CMD, as specified in the Dockerfile. This step is essential since these configurations must be applied post-container startup. However, this action supersedes the original image's CMD. Consequently, to operate the container akin to the base image's default behavior, it's crucial to establish the original image's entry point after the setup-ssh.sh script runs.

With the Dockerfile established, the next step involves creating its image.

Access the folder where the files were saved and run the following command:

docker build -t your-image:tag .

Navigate to the directory where the files are saved. Run the following command

docker tag your-image:tag your-registry.com/your-image:tag

Finally, the newly created image equipped with SSH support can be pushed to the registry

docker push username/your-image:tag

Now that the new image has been defined, you can create your container and access it via SSH. Ensure you configure TCP port 22, or the port you defined on your Dockerfile.