Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove existing docker containers/images GitLab CI

Tags:

gitlab

I have a GitLab CI pipeline with 3 steps:

  • build
  • release
  • deploy

In my deploy step, I; SSH into my DO box, login to GitLab registry, pull down the latest docker image & run it. I am also attempting to remove existing containers/images using:

docker rm -f $(docker ps -aq)
docker rmi $(docker images -q)

.gitlab.yml

cache:
  key: "${CI_COMMIT_REF_NAME} node:latest"
  paths:
    - node_modules/

stages:
  - build
  - release
  - deploy

build:
  ...

release:
  ...

deploy:
  stage: deploy
  image: gitlab/dind:latest
  only:
    - master
  environment: production
  when: manual
  before_script:
    - mkdir -p ~/.ssh
    - echo "${DEPLOY_SERVER_PRIVATE_KEY}" | tr -d '\r' > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - eval "$(ssh-agent -s)"
    - ssh-add ~/.ssh/id_rsa
    - ssh-keyscan -H ${DEPLOYMENT_SERVER_IP} >> ~/.ssh/known_hosts
  script:
    - ssh root@${DEPLOYMENT_SERVER_IP}
      "echo 'CONTAINERS';
      docker ps -aq;
      echo 'IMAGES';
      docker images -q;
      docker rm -f $(docker ps -aq);
      docker rmi $(docker images -q);
      docker login -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD} ${CI_REGISTRY};
      docker pull ${CI_REGISTRY}/${CI_PROJECT_PATH}:latest;
      docker run -d ${CI_REGISTRY}/${CI_PROJECT_PATH}:latest;"

I log out the result of the container/image IDs before I attempt to remove them. The (partial) output of that build step is: enter image description here

You can see that the docker ps -aq command logs out 1 existing container ID & the docker images -q logs out 4 existing image IDs. Why then am I getting the error below of:

"docker rm" requires at least 1 argument

...and...

"docker rmi" requires at least 1 argument

when I can see that there are existing containers/images?

like image 241
wmash Avatar asked Sep 07 '19 16:09

wmash


2 Answers

seem like the issue with subshell but You can try with xargs if there is an issue with subshell in gitlib.

      echo 'IMAGES';
      docker images -q;
      docker ps -aq | xargs docker rm -f;
      docker images -q | xargs docker rmi;
like image 145
Adiii Avatar answered Sep 22 '22 09:09

Adiii


Instead of relying on bash subshell $(...), you would try the

  • docker container prune
  • docker image prune

That would detect stopped/dangling objects and remove them.

like image 29
VonC Avatar answered Sep 22 '22 09:09

VonC