Building DevSecOps solutions using AWS, Terraform and Kubernetes

How to SSH into docker containers

  • 19th March 2023
Docker SSH

Introduction

SSH access to a container is generally not recommended as containers are meant to be ephemeral and stateless. However, there are some cases where SSH access may be necessary, such as for debugging or troubleshooting purposes.

The purpose of this article is to give you a quick reference point for how to connect to different containers running in different clusters.

SSH into a Docker Container

Docker SSH

  1. Find the name of the container you want to SSH into:
docker ps
  1. You can now execute a shell session on the container by running the following command:
docker exec -it <container-name> /bin/bash

SSH into a Docker Compose Container

Docker Compose SSH

  1. Find the name of the container you want to SSH into:
docker-compose ps
  1. You can now execute a shell session on the container by running the following command:
docker-compose exec <service-name> /bin/bash

SSH into a ECS Container

ECS Container SSH

  1. Connect to the AWS CLI with the appropriate permissions.

  2. Log into the AWS console and find the details for the container you would like to SSH into.

  3. You can now execute a shell session on the container by running the following command:

aws ecs execute-command \
    --cluster <cluster-name> \
    --task <task-id> \
    --container <container-id> \
    --command "/bin/bash" \
    --interactive \
    --region eu-west-2

SSH into a Kubernetes Container

Kubernetes Container SSH

  1. Authenticate access to kubectl, this varies per cloud. For example in AWS EKS.

  2. Find the name of the container you want to SSH into:

kubectl get pods
  1. You can now execute a shell session on the container by running the following command:
kubectl exec -it <pod-name> -c <container-name> -- /bin/bash

Summary

Hopefully this gives you a quick reminder of how to connect to docker containers in different environments.

As someone who works on a large number of different clusters I find this quick reference sheet invaluable in my day to day work, particularly while debugging containers that are not behaving as expected.

Rhuaridh

Please get in touch through my socials if you would like to ask any questions - I am always happy to speak tech!