Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Docker - Enter a Running Container With New TTY


Since docker 1.3, you can use docker exec -it [container-id] bash.

To make life easier, I created the script below



if [ "$#" -ne $EXPECTED_NUM_ARGS ]; then
    # user didn't specify which container ID, assume the latest one
    CONTAINER_ID=`/usr/bin/docker ps -q --no-trunc | /bin/sed -n 1p`
    /usr/bin/docker exec -it $CONTAINER_ID env TERM=xterm bash
    # enter the container the user specified
    /usr/bin/docker exec -it $1 env TERM=xterm bash

Notice that we are setting our terminal to xterm. This resolves a few little niggles that arise otherwise.

You can "install" with:

wget \
  && sudo mv -i docker-enter /usr/bin/docker-enter \
  && sudo chmod +x /usr/bin/docker-enter

Now you can just run docker-enter $CONTAINER_ID, but best of all, if just want to enter the last container you spawned, just run the command docker-enter without having to look up the ID. This is especially useful on hosts where you are just running one container.

Powershell Version

A colleague at work kindly provided me with the powershell version below:

function docker-enter
    $id = (docker container ls | select-string $name) -replace "(\w)\s+.*$name$", $1
    docker exec -it $id bash


Last updated: 22nd July 2021
First published: 16th August 2018