Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Docker - Enter a Running Container With New TTY

Steps

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

To make life easier, I created the script below

#!/bin/bash 

EXPECTED_NUM_ARGS=1;

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
else
    # enter the container the user specified
    /usr/bin/docker exec -it $1 env TERM=xterm bash
fi

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

You can "install" with:

wget https://files.programster.org/public/docker-enter \
  && 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
{
    param($name)
    $id = (docker container ls | select-string $name) -replace "(\w)\s+.*$name$", $1
    docker exec -it $id bash
}

References

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

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch