Docker attach to running container

Attach to the running Docker container interactively using FZF.

Install FZF: brew install fzf

Add the following function to the .bashrc or .zshrc

1dex() {
2 CONTAINER=$(docker ps | grep -v CONTAINER | awk '-F ' ' {print $NF}' | fzf)
3 if [ ! -z "$CONTAINER" ]
4 then
5 docker exec -it "$CONTAINER" bash
6 fi
7}

Let's break it down:

  1. docker ps Lists all running Docker containers
  2. grep -v CONTAINER Filter out headers from docker ps output
  3. awk '-F ' ' {print $NF}' Extracts only container names
  4. fzf Select a container using FZF
  5. if [ ! -z "$CONTAINER" ] Checking if container was selected
  6. docker exec -it "$CONTAINER" bash - opens an interactive shell in the selected container.

More useful functions in my dotfiles repo

Interactively attach to running Docker container using FZF