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.
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