Home > Software engineering >  Exit from docker using make file
Exit from docker using make file

Time:06-30

I am trying to create a make file to run the docker commands.

start:
    $(info Make: Starting container.)
    docker run -it --rm -v $(shell pwd):/mnt -w /mnt build:focal
 
stop:
    $(info Make: Stopping container.)
    exit

When I run make start, the docker container starts and the current directory is /mnt but when I run make stop it prints exit in the terminal rather than exiting the docker container. So, to stop, I must type exit or ctrl c again in the terminal. Is it possible to close the container using makefile from inside the container?

$make start
Make: Starting container.
docker run -it --rm -v /data/demo:/mnt -w /mnt build
builduser@6a1958f9d0cc:/mnt$ ls
Makefile
builduser@6a1958f9d0cc:/mnt$ make stop
Make: Stopping container.
exit

CodePudding user response:

You can't use make this way in general. You can try it from your host shell: no matter how many times you run make stop it will not exit the containing shell.

There's a couple of subprocesses involved here. make itself is a subprocess, and then for each command in each rule it runs /bin/sh -c (or something else from the Make $(SHELL) variable). So this command runs /bin/sh -c 'exit', which launches another subprocess. That shell subprocess exits but nothing else. If Make had another target to build, it would build it.

Whatever work it is you want to do inside a container, I'd suggest setting up the container to just do that work. Don't involve an interactive shell. If you can manage it, try to avoid having a long-running container that you execute multiple commands in; instead, run one-off containers with docker run --rm.

BUILD_IMAGE := image

some-file.txt:
        docker run --rm -v $(PWD):/data -w /data $(BUILD_IMAGE) \
          touch some-file.txt

some-file-2.txt: some-file.txt
        docker run --rm -v $(PWD):/data -w /data $(BUILD_IMAGE) \
          sh -c 'cat some-file.txt some-file.txt > some-file-2.txt'

Rather than try to invoke Docker from within your Makefile, it may be easier to write a "normal" Makefile, then run the whole thing in a container.

some-file.txt:
        touch "$@"

some-file-2.txt: some-file.txt
        cat "$<" "$<" > "$@"
docker run -v "$PWD:/build" -w /build build-image make
  • Related