Docker - Enter a Running Container With New TTY

Generic Method - Docker Enter

Since docker 1.3, you can use
docker exec -it [container-id] bash
. To make this easier, I create a file at
/usr/bin/docker-enter
with the following contents.
#!/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
Now make it executeable:
sudo chmod +x /usr/bin/docker-enter

Now you can just run

docker-enter $container-id
or if you just want to enter the last container you spawned, just run the command
docker-enter

Outdated Method - Here for reference

This method is going to utilize nsenter, but by building a wrapper that works with it to make life simple.

Installation (Run once on host)

sudo apt-get install build-essential -y
wget https://raw.githubusercontent.com/Pithikos/docker-enter/master/docker-enter.c
gcc docker-enter.c -o docker-enter
chmod +x docker-enter
sudo mv docker-enter /usr/sbin/.
sudo rm docker-enter.c

Whenever you need to enter a container, simply run the command below:

sudo docker-enter $SHORT_CONTAINER_ID
Use
docker ps
to find out the container ID you want.

Connecting to LXC container

If you have set docker to use LXC containers then you can run the steps below which do not require you to compile anything on the host, but you have to use the long ID for the container in order to enter it.

    As of Docker 0.9, one needs to manually set the docker service to use the LXC engine.
    Grab the full container ID
    docker ps --notrunc
    Now run an LXC attach command with the full ID.
    lxc-attach -n [container ID]

References

No comments:

Post a Comment