Search code examples
dockerdocker-container

stop and remove docker container based on Port assigned


Below code will stop and remove a Docker container -

docker rm -f CONTAINER_ID

However it require Container ID, which I take from running another code docker ps to get the ID that is using a typical port (e.g. 0.0.0.0:8383->8383/tcp) from the column PORTS.

I am looking for a way to bundle these 2 codes into a single one with PORT as variable so that I do not need to feed manually the container ID obtained from PORTS.

Is there any possibility?


Solution

  • Try this:

    PORT=8383
    docker container ls --format="{{.ID}}\t{{.Ports}}" |\
    grep ${PORT} |\
    awk '{print $1}'
    

    The first command lists the running containers but only outputs the container ID and the ports. The result is piped into grep to grab the container of interest. The awk commands grabs the container ID.

    Test

    • Create 3 Nginx containers on :7777,:8888,:9999.
    • Then, find the containers by their ports, stop and remove them.
    for PORT in 7777 8888 9999
    do
      docker run --detach --publish=${PORT}:80 nginx
    done
    
    docker container ls
    
    for PORT in 7777 8888 9999
    do
      echo "Looking for a container on port: ${PORT}"
      ID=$(\
        docker container ls --format="{{.ID}}\t{{.Ports}}" |\
        grep ${PORT} |\
        awk '{print $1}')
      echo "Found Container ID: ${ID}"
      echo "Stopping and removing it"
      docker container stop ${ID} && docker container rm ${ID}
    done