1

I wrote a script to build and run a docker container:

docker build --rm -t 'mine' . && docker run -p 3000:3000 -it 'mine' 

If I run it two times in a row, the previous one is already running so it doesn't start. To fix this, I wrote a line to kill all docker containers:

docker kill $(docker ps -q) || true docker build --rm -t 'mine' . && docker run -p 3000:3000 -it 'mine' 

This works, but now I have multiple projects on my machine that use docker, and this kills all of them, which isn't what I want. I only want it to kill the docker container in this project.

How can I modify this script so it only kills the docker container(s) that are started in the second line?

6
  • Have a look at docker-compose Commented Sep 6, 2019 at 22:08
  • 1
    Possible duplicate of Kill a Docker Container Commented Sep 6, 2019 at 22:28
  • @jeremysprofile I'd say it's not a dupe because the answer has this line: "Then copy the CONTAINER ID of the running container and execute the following command". I want to do this all in a script Commented Sep 6, 2019 at 22:32
  • 1
    @DanielKaplan, I'd say it is a dupe because if you scrolled down one more answer, there is an alternative that says docker kill container_name. In your case, it would be docker kill mine Commented Sep 6, 2019 at 22:36
  • 1
    @jeremysprofile Actually, I tried that and it didn't work. I don't say docker kill mine, I say docker kill container_name which I have to get from docker container ls. Therefore, I don't think this is the same question. I'm asking for a one-line script to do all these steps, not a manual series of steps. Commented Sep 6, 2019 at 22:46

2 Answers 2

1

You should provide a container name so that you can kill it by name. You'll also have to use --rm so you can restart it easily next time:

Terminal 1:

docker run -it --rm --name killMe alpine:latest /bin/sh 

Terminal 2:

docker container ls > CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES > 0113b3fea7dd alpine:latest "/bin/sh" 19 seconds ago Up 18 seconds killMe docker kill killMe # the container in my first terminal is now stopped docker run -it --rm --name killMe alpine:latest /bin/sh # it started again 
Sign up to request clarification or add additional context in comments.

Comments

0

I came up with this:

docker kill $(docker container ls | tail -1 | awk '$0 ~ /mine/ {print $NF}') 

Let's start with the $(...) first. It says, list the containers, cut off the header, print the last column of any line that has mine in it (the name of my container tag). The last column is the name of the container.

I take this result and pass it into docker kill <result>. This probably wouldn't work if there were multiple running containers with mine in it, but since I can't have two running at the same time, I'm okay with this limitation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.