Trying to persist docker images and expose ports on local runner

Problem to solve

Hello I have been struggling with this issue for the last couple of weeks. I have been attempting to use the managed gitlab server and shared runner to build an image and then pull the image into a local ubuntu server using a self managed runner and run it. My issue is the safest option I have been aware of is to have the self managed runner on my local server use a docker executor. I am having difficulty getting this working, the containers I am running end up getting erased when the job is done and I am not sure on how to expose the ports in them. For context the containers are serving an HTML page. Sorry if this is not super thorough, I am still super new to all of this.

Steps to reproduce

My setup is a git repo that contains a build folder with one html file. Alongside that is a docker file to build the docker image and the .yaml file

Configuration

My .gitlab-ci.yml file

variables:
  IMAGE_NAME: options-react
  IMAGE_TAG: 1.0

stages:
  - build
  - test

image: docker:20.10.16

services:
    - name: docker:20.10.16-dind
      alias: docker

build_image: 
  stage: build
  script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin
    - docker build --build-arg API_URL=$API_URL --build-arg DB_USER=$DB_USER -t $CI_REGISTRY/{group}/{project}/$IMAGE_NAME:$IMAGE_TAG .
    - docker push $CI_REGISTRY/{group}/{project}/$IMAGE_NAME:$IMAGE_TAG

deploy_image:
  stage: test
  variables: 
    DOCKER_TLS_CERTDIR: ""
  tags: 
    - prod
  script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin
    - docker pull $CI_REGISTRY/{group}/{project}/$IMAGE_NAME:$IMAGE_TAG
    - docker run -d -p 4012:4012 $CI_REGISTRY/{group}/options-creator/$IMAGE_NAME:$IMAGE_TAG

Versions

  • Self-managed
  • GitLab.com SaaS
  • Dedicated

Hi there,

You have to understand the following: your CI job is executed INSIDE of a container on a VM where is the runner. Very likely, this VM is not the VM where you want to deploy your image to.

In order to deploy, you have to do what you would normally do - ssh into the target VM (where you want to deploy) and then run docker login, docker pull and docker run or whatever you need to deploy.

There are plenty of examples on forum how to do this, e.g.: Question on Deploy phase of gitlab-ci.yaml - #2 by paula.kokic

Hope this helps! :slight_smile:

P.S. If you DO want to deploy the image on exactly the same VM as your runner (which is not normally the use case), it would be better to use shell executor → then your commands would be executed directly on the VM instead of a container.