🐶
Kubernetes

SSH into Kubernetes Pod: A Quick Guide

By Jan on 02/09/2025

Learn different ways to establish secure shell (SSH) connections to a Kubernetes pod for debugging and troubleshooting.

SSH into Kubernetes Pod: A Quick Guide

Table of Contents

Introduction

While directly SSHing into a Kubernetes pod isn't the typical approach, you can achieve similar results using kubectl exec. This article outlines the steps to connect to a pod using kubectl exec and highlights alternative methods for interacting with your applications running in Kubernetes.

Step-by-Step Guide

While directly SSHing into a Kubernetes pod isn't the typical approach, you can achieve similar results using kubectl exec.

  1. Ensure SSH server is running: If your pod needs an SSH server, include it in your Dockerfile.

    RUN apt-get update && apt-get install -y openssh-server
  2. Expose the SSH port (optional): If you need to connect from outside the cluster, expose the port in your service definition.

    ports:
    - protocol: TCP
      port: 22
      targetPort: 22
  3. Connect to the pod: Use kubectl exec to run commands inside the pod.

    kubectl exec -it <pod-name> -n <namespace> -- bash

Alternatives to SSH:

  • kubectl logs: View container logs.
  • kubectl describe pod: Get detailed pod information.
  • Debugging tools: Use debuggers within your application code.

Important Considerations:

  • Security: Exposing SSH ports can introduce security risks.
  • Ephemeral nature of pods: Pods can be deleted and recreated, making persistent SSH connections unreliable.
  • Kubernetes-native tools: Leverage Kubernetes tools for managing and debugging applications.

Code Example

This code provides a basic example of how to debug a Python Flask application running inside a Kubernetes pod. It uses an SSH server within the Docker container to allow direct access to the pod for debugging. The Dockerfile includes instructions for installing SSH and exposing port 22. The Kubernetes deployment configuration exposes this port through a service. After deployment, you can use kubectl exec to connect to the running pod and debug the application. However, it's crucial to note that exposing SSH in production is highly discouraged due to security risks.

This example demonstrates how to use kubectl exec to debug a simple Python Flask application running in a Kubernetes pod.

1. Dockerfile (with SSH server):

FROM python:3.9-slim-buster

WORKDIR /app

# Install dependencies
RUN apt-get update && apt-get install -y openssh-server
RUN pip install flask

# Add your application code
COPY . /app

# Expose port and start Flask app
EXPOSE 5000
CMD ["python", "app.py"]

# SSH configuration
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

2. Kubernetes Deployment (with SSH port exposed):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: flask-app
  template:
    metadata:
      labels:
        app: flask-app
    spec:
      containers:
      - name: flask-app
        image: <your-docker-image>
        ports:
        - containerPort: 5000
        - containerPort: 22 # Exposing SSH port
---
apiVersion: v1
kind: Service
metadata:
  name: flask-app-service
spec:
  selector:
    app: flask-app
  ports:
  - protocol: TCP
    port: 5000
    targetPort: 5000
  - protocol: TCP # Exposing SSH port in service
    port: 22
    targetPort: 22
  type: LoadBalancer

3. Connect to the pod and debug:

# Get the pod name
kubectl get pods -l app=flask-app

# Connect to the pod using kubectl exec
kubectl exec -it <pod-name> -n <namespace> -- bash

# Once inside the pod, you can debug your application
# For example, you can check running processes, view logs, etc.
ps aux
cat /app/app.py

Remember: This example is for demonstration purposes only. Exposing SSH ports in production environments is highly discouraged. Use Kubernetes-native tools and best practices for debugging and managing your applications.

Additional Notes

  • SSHing into a Kubernetes pod is generally not recommended. Kubernetes offers better, more secure ways to interact with your applications. Treat pods as ephemeral units that can be destroyed and recreated.
  • Focus on using Kubernetes-native tools for debugging and troubleshooting. kubectl logs, kubectl describe, and kubectl exec are your primary tools for understanding and interacting with your applications.
  • If you absolutely must use SSH, prioritize security.
    • Don't expose the SSH port publicly. Use port forwarding or a VPN for secure access.
    • Use strong passwords or SSH keys. Never rely on default credentials.
    • Disable root login if possible. Create a dedicated user with limited privileges for SSH access.
  • Consider alternatives to SSH for debugging.
    • Remote debuggers: Integrate debuggers directly into your application code for more powerful debugging capabilities.
    • Ephemeral containers: Use kubectl debug to create temporary containers in your pod for troubleshooting.
  • Treat SSH as a last resort. Explore all other options before resorting to SSH for interacting with your Kubernetes pods.

Summary

While not recommended, accessing a Kubernetes pod like an SSH server is possible. This table summarizes the process and key considerations:

Feature Description
SSH Server Must be installed in the pod's Docker image (e.g., using apt-get install openssh-server).
Port Exposure Optionally expose port 22 in your service definition to connect from outside the cluster.
Connection Use kubectl exec -it <pod-name> -n <namespace> -- bash to run commands inside the pod.
Alternatives Consider Kubernetes-native tools like kubectl logs, kubectl describe pod, and debuggers for safer and more reliable workflows.
Security Exposing SSH ports can introduce significant security risks.
Pod Ephemerality Pods can be deleted and recreated, making persistent SSH connections unreliable.
Best Practices Prioritize Kubernetes-native tools for managing and debugging applications.

Conclusion

In conclusion, while SSHing into Kubernetes pods might seem like a familiar approach, it's crucial to prioritize Kubernetes-native tools and best practices for interacting with your applications. kubectl exec offers a safer and more controlled way to execute commands within a pod. Remember that exposing SSH ports can introduce security risks, and the ephemeral nature of pods makes persistent SSH connections unreliable. Leverage the power of Kubernetes and its dedicated tools for a more robust and secure approach to managing and debugging your applications.

References

  • How to SSH into a POD as -u 33 : r/kubernetes How to SSH into a POD as -u 33 : r/kubernetes | Posted by u/GoingOffRoading - 4 votes and 18 comments
  • Get a Shell to a Running Container | Kubernetes Get a Shell to a Running Container | Kubernetes | This page shows how to use kubectl exec to get a shell to a running container. Before you begin You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
  • Ssh with port 22 into k8s pod as non root user - Discuss Kubernetes Ssh with port 22 into k8s pod as non root user - Discuss Kubernetes | Asking for help? Comment out what you need so we can get more information to help you! Cluster information: Kubernetes version: 1.19 Cloud being used: on-perm Installation method: i believe kubeadm Host OS: ubuntu Hi, I have a business requirement to SSH as a non-root into kubernetes pod and this is already in traditional server setup, just moving the same to k8s. Have installed metallb. I created my set of private and public keys. Add the public key and sshd_config ( PasswordAuthentic...
  • How To SSH Into A K8s Pod - Valewood DevOps Consulting How To SSH Into A K8s Pod - Valewood DevOps Consulting | Taking the paradigm shift from running applications on servers to running them in containers is quite the mental jump. The technology industry has spent the last 50 years creating technology to accelerate on top of servers whether they are physical or virtual.
  • SSH into Kubernetes pod without public IP access | by David Finson ... SSH into Kubernetes pod without public IP access | by David Finson ... | In this guide we’ll demonstrate how to SSH into a Kubernetes pod without any external tools or services bridging between the pod and the…
  • Run an OpenSSH server as a bastion on a Kubernetes Pod ... Run an OpenSSH server as a bastion on a Kubernetes Pod ... | Ever needed a convenient bastion/jump-host to something hidden away in your internal private subnets? Have a Kubernetes cluster up and running already? This blog post walks you through how to spin up an OpenSSH server in a pod for easy SSH port-tunneling
  • SSH into a Kubernetes cluster - Octopus Deploy SSH into a Kubernetes cluster - Octopus Deploy | Learn how to set up a SSH bastion host in your Kubernetes cluster.
  • Mounting a Kubernetes Secret as a single file inside a Pod | Jeff ... Mounting a Kubernetes Secret as a single file inside a Pod | Jeff ... | Jan 15, 2019 ... Recently I needed to mount an SSH private key used for one app to connect to another app into a running Pod, but to make sure it was done ...
  • How to use ssh to Z-JH in local cluster - Zero to JupyterHub on ... How to use ssh to Z-JH in local cluster - Zero to JupyterHub on ... | It’s a good idea for data scientist. They can use vscode to link the single note-book by ssh , it useful to debug . Now , Let me say how I practice . 1、The latest helm version 1.2.0 is seem stable . 2、Use jupyterhub-ssh to build a jupyterhub-ssh service.By the way, we have choose a version at first. https://yuvipanda.github.io/jupyterhub-ssh/index.yaml 3、Use the special value for zero-to-jupyter. proxy.https.enable must be true. for TLS proxy.https.type must be letsencrypt. for start de...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait