1

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.

AWS_Lernar
  • 627
  • 2
  • 9
  • 26
  • You can give your container also a name (https://docs.docker.com/engine/reference/run/#name---name) or you can get the container id with docker `docker ps -q` – thopaw Nov 04 '19 at 06:42

3 Answers3

3

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

LinPy
  • 16,987
  • 4
  • 43
  • 57
1

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
Adiii
  • 54,482
  • 7
  • 145
  • 148
0

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

docker image prune

Let me know if you face any issues running it.

ZygD
  • 22,092
  • 39
  • 79
  • 102