Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I attach to a running Docker container later?

Tags:

docker

I want to simply start a docker container that executes some java code which ends up starting JBoss.

This is working fine except I can't figure out how to attach to the container again and get back to the bash prompt.

This is how I start my container:

docker run -i -t -p 80:80 -v /tmp/automatefiles:/automatefromhost jboss bash -c 'cd automatefromhost; chmod 777 *.*; ./runAutomate.sh;'

This is the runAutomate.sh

/usr/bin/java -cp Automate.jar -Djava.net.preferIPv4Stack=true net.Automate > automateresults &
tail -f automateresults

Now I have to do the tail at the end to keep the container running after its finished running my Automate code. The end result of this is that Jboss is running with my app configured correctly.

Now when I try to attach to the container again I just get a blank screen with no prompt...and can't get back to the prompt within the container. So no way to interact with the container after it has started.

Any ideas on how I can start the container, keep it running and then attach to the container later and be back in the prompt to do things like ls, tail etc .

EDIT: I ended up doing this:

I copied this approach : https://stackoverflow.com/a/20932423/1519407 and added to my script

while ( true )
    do
    echo "Detach with Ctrl-p Ctrl-q. Dropping to shell"
    sleep 1
    /bin/bash
done

This still seems kind of hacky but it works...I think its probably better to go down the path of installing ssh onto the container or using something like http://phusion.github.io/baseimage-docker/

like image 344
tinytelly Avatar asked Dec 06 '22 01:12

tinytelly


2 Answers

Just putting in code words.

docker attach container_name
ctrl p ctrl q

exit command stops the container, where as ctrlp and ctrl q just detaches that container and keeps it running

Update: For those who don't know already, from docker 1.3 or so, we can use exec command for attaching to a container and exiting it without hassle.

eg: docker exec -it container_name bash

You can just type exit when needed, it will exit the container and still keeps it running.

like image 180
phoenix Avatar answered Jan 05 '23 23:01

phoenix


The command below:

docker exec -it [container id/name] /bin/bash

can attach a running container.

like image 45
zcmyworld Avatar answered Jan 05 '23 23:01

zcmyworld