AWS_Lernar
AWS_Lernar

Reputation: 659

deleting existing docker images from EC2 using Jenkins

I have to run some containers from the images present in AWS ECR.As i need to automate this i am using Jenkins.

I have 4 ECR repositories as soon as a new version of image comes in this repository my jenkins job will trigger and create a new container.So as the code of microservice is changing and i am getting new image in ECR i have to delete the old container and run the new one on same port.

I am using "Send file or execute commands over SSH" of Jenkins to do this. Then i am providing commands like below

   aws ecr get-login --no-include-email > login.sh
   bash login.sh
   docker pull 944198216610.dkr.ecr.us-east-1.amazonaws.com/demo- 
     docker:latest
   docker run -d -p 8081:80 944198216610.dkr.ecr.us-east- 
        1.amazonaws.com/demo-docker:latest

Now the problem is whenever i get new image i have to stop the earlier container running and for that i need container-id. I dont know to fetch container-id here to stop the container.Any help in this is highly appreciated.

Upvotes: 1

Views: 2072

Answers (3)

Umesh Dande
Umesh Dande

Reputation: 1

Following is the command to remove downloaded images from EC2 server:

docker image prune

Let me know if you face any issues running it.

Upvotes: 0

Adiii
Adiii

Reputation: 59946

The answer is already given but one important thing that I will never suggest to remove container using

docker rm -f

which sends SIGKILL directly without grace period.

The best way to deal is to first stop the container then remove the container, It sends SIGTERM first, then, after a grace period, SIGKILL.

Also if you are not running ECS then the hardcoded name is enough, as you are not running both containers simultaneously, so

docker run --rm --name my_container -d -p 8081:80 944198216610.dkr.ecr.us-east-1.amazonaws.com/demo-docker:latest

so during deployment all you need docker stop my_container it will stop and the container also will release the name, so you are good to go deploy again with same name.

docker run --rm --name my_container -d -p 8081:80 944198216610.dkr.ecr.us-east-1.amazonaws.com/demo-docker:latest

Upvotes: 1

LinPy
LinPy

Reputation: 18578

to get the containers you may use:

docker ps -q --filter "ancestor=944198216610.dkr.ecr.us-east- 
        1.amazonaws.com/demo-docker:latest"

so to delete them :

docker rm -f $(docker ps -q --filter "ancestor=944198216610.dkr.ecr.us-east- 
        1.amazonaws.com/demo-docker:latest")

you can add -a to docker ps to delete not running containers also

ancestor Filters containers which share a given image as an ancestor. Expressed as image-name[:tag], image id, or image@digest

Upvotes: 3

Related Questions