Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a running Docker container from within the same terminal?

Tags:

linux

docker

I've built a Dockerfile which ends with compiling my (Golang) code and then running the compiled binary:

# Compile my Go code
RUN go build -o bin *.go

# Run the binary
CMD /root/src/whisky/bin

After building the image (docker build -t whisky .) I run the image (docker run --name whisky whisky_image) and the program starts to give output in the terminal.

When I run the program from my laptop I can always stop it using CTRL+C, but now it's running inside the container and hitting CTRL+C doesn't do anything. The container simply keeps giving output and nothing stops.

I can still stop the container from another terminal docker stop whisky, but I guess there should be a nicer way.

Does anybody know the recommended way to stop the command in the container or stop the whole container from the same terminal?

[EDIT]

From the answers given I learned I can run the container in detached mode using -d and then tail the container logs using docker logs container_id --follow. Although that works I prefer to run the container directly (in non-detached mode) because then I can't make the mistake of running it in the background and forgetting about it.

Does anybody know how I can run the container in a way that I can stop it from the same terminal by hitting CTRL+C?

like image 367
kramer65 Avatar asked Nov 12 '19 11:11

kramer65


3 Answers

you can use '-d' --> in detached mode

[EDIT] To add. After that you can tail to logs using

docker logs container_id --follow
like image 55
Raju Shikha Avatar answered Oct 15 '22 11:10

Raju Shikha


Allocate a pseudo-tty (-t) and then you can control output by hitting CTRL+C:

$ docker run --name whisky -t whisky_image
^C

But container will be still running, so add also stdin (-i):

$ docker run --name whisky -ti whisky_image
^C

But container will be still there (see docker ps -a - in exited status), so you may add cleanup flag --rm:

$ docker run --name whisky --rm -ti whisky_image
^C

See Docker run doc for more details.

like image 38
Jan Garaj Avatar answered Oct 15 '22 11:10

Jan Garaj


you need to run your container using init

docker run --init --name whisky whisky_image

then kill it using Ctrl+C

the initwill start your program as PID 1

like image 33
LinPy Avatar answered Oct 15 '22 09:10

LinPy