Gitlab-CI error upon deploying Docker Image on swarm mode

Hi i have problem with updating / changing image of my service on the server running Docker swarm mode.
Here is the process of manually updating the service.

  1. push the project to gitlab from local machine.
  2. pull the project from gitlab in server.
  3. build a Docker image as my-project:latest
  4. tag my-project:latest as
  5. i push the image using docker push
  6. i run docker stack deploy -c ~/docker-stack.yml api --with-registry-auth
    and it works fine.

However if i move the codes above into a gitlab-ci.yml despite of ending the job successfully i get an error when it is trying to update the service.

Updating service api_backend (id: r4gqmil66kehzf0oehzqk57on)
 image could not be accessed on a registry to record
 its digest. Each node will access independently,
 possibly leading to different nodes running different
 versions of the image.

Also the gitlab runner is executing commands in Shell mode.
I have tried different solutions as you can see i’m even using the --with-registry-auth flag.

To summarize this:
everything works fine if i enter the codes manually but i get an error when i use gitlab-ci.yml.

Source: StackOverflow