[SOLVED] Replace a running container in GitLab pipeline

Hi,
I’m trying to set up a Gitlab pipeline with two stages :

  • A build stage that build a docker image
  • A deploy stage launching a container with the built image

But I don’t find how to remove the container from the previous deploy (during the previous push).

I tried two methods :

  • docker rm -f my-container : but the container is not always running and the command gives an error when it’s not
  • docker ps -a | grep 'my-container' | awk '{print $1}' | xargs --no-run-if-empty docker rm -f
    It seems correct but GitLab gives a mysterious Error that stops the deployment : ERROR: Build failed: exit code 1

How do I remove the previous container before launching a new one ?

Thank you for your help

I ran into a similar issue, ended up with this line:

docker rm -f `docker ps -a --no-trunc | grep my-container_  | awk '{ print $1}'` 2> /dev/null || exit 0

However, I am running that command from another script that gitlab-ci calls.

Assuming you’re running on Linux, you should be able to ignore the build fail with:

docker rm -f my-container 2>/dev/null || exit 0

I just realized the exit 0 may not be what you want. In my case it was fine until I wanted to run another command after the docker rm -f command. With || exit 0 the wrapper script exited, skipping the next step. Switching || exit 0 to || true keeps everything moving along.

docker rm -f my-container 2>/dev/null || true

Thank a lot ! It does the job.

That’s a good working solution.

I did something a little bit different.
What I did was to add a cleanup stage which would remove the docker container at the end of the build/test run.
You can probably specify that stage to run “when: always” to force it to remove the container regardless of build/test success or failure.