docker restart container failed: “already in use”, but there's no more docker image

前端 未结 3 956
长情又很酷
长情又很酷 2021-01-31 15:03

I first got my nginx docker image:

docker pull nginx

Then I started it:

docker run -d -p 80:80 --name webserver nginx
         


        
3条回答
  •  梦毁少年i
    2021-01-31 15:28

    While the great answers are correct, they didn't actually solve the problem I was facing.

    How To:

    Safely automate starting of named docker container regardless of its prior state

    The solution is to wrap the docker run command with an additional check and either do a run or a stop + run (effectively restart with the new image) based on the result.

    This achieves both of my goals:

    • Avoids the error
    • Allows me to periodically update the image (say new build) and restart safely
    #!/bin/bash
    # Adapt the following 3 parameters to your specific case
    NAME=myname
    IMAGE=myimage
    RUN_OPTIONS='-d -p 8080:80'
    
    ContainerID="$(docker ps --filter name="$NAME" -q)"
    
    if [[ ! -z "$ContainerID" ]]; then
        echo "$NAME already running as container $ContainerID: stopping ..."
        docker stop "$ContainerID"
    fi
    echo "Starting $NAME ..."
    exec docker run --rm --name "$NAME" $RUN_OPTIONS "$IMAGE"
    

    Now I can run (or stop + start if already running) the $NAME docker container in a idempotent way, without worrying about this possible failure.

提交回复
热议问题