DEV Community

Varun Gujarathi
Varun Gujarathi

Posted on

Set up a CI pipeline in GitLab to build and push Docker Images from a Git repository

DevOps has become a very essential role in today’s software development teams. As we all know that the main job of a DevOps engineer is to handle integrations and deployments in an Agile environment. It covers operations like setting up CI/CD pipelines, containerizing applications, setting up servers, etc.

In an agile environment, teams continuously commit their changes to a version control system, these commits include new features, improvisations over old features, and bug fixes in the system. To reflect these changes on the Testing/UAT/Production servers, pipelines are set up that can pull the latest code from the version control system, build the image and push it to the corresponding container registry. Generally, Docker supports pipelining only from GitHub & BitBucket, unfortunately, with GitLab, you need to set up this pipeline from your GitLab repo itself and not from Docker.

Follow the below steps to set up your pipeline. (Note: Assuming that you have created your Docker Hub registry and a GitLab repo)

Step 1

Create a .gitlab-ci.yml file in the project
The .gitlab-ci.yml file is a YAML file that holds the configurations for your Docker Hub. A GitLab repo consisting of this file runs the commands in the file whenever a new commit is pushed to the repo.
Refer here:

The YAML file should look like this

image: docker:latest
    - docker:dind
    LATEST_VER: {imagename:tagname}
    - Build image and Push to Docker Hub
docker build and push:
    stage: Build image and Push to Docker Hub
        - master
        - echo "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin
        - docker info
        - docker build -t $LATEST_VER .
        - docker push $LATEST_VER
Enter fullscreen mode Exit fullscreen mode

Step 2

Set CI/CD variables in GitLab

  1. Log in to GitLab using valid credentials.
  2. Go to the repository.
  3. Scroll down the left panel to find the ‘Settings’ options.
  4. Click on the ‘CI/CD’ sub-option.
  5. Now find the ‘Variables’ sub-section (fourth option) and expand it.
  6. Add two new variables using “REGISTRY_PASSWORD” and “REGISTRY_USER” as keys. The values should be the password and username of your Docker registry, respectively

Done! now make changes and push your code. Check the ‘CI/CD -> Pipelines’ section in your GitLab repo menu to check the status of your pipeline.

Top comments (0)