РЭДЛАЙН
Лучшие решения для Вас и Вашего бизнеса!
На нашем сайте вы можете получить информацию о веб-разработке, обслуживании и продвижении сайта. Интернет-маркетинге. SEO (поисковой оптимизации). Контекстной и медийной рекламе в Интернете. SMM. Регистрации доменов и хостинговых услугах. И современном дизайне сайтов. Вообщем того что касается веб-разработки, а также много другой полезной информации из мира интернета, бизнеса и интернет-технологий...
Создаем доступные и современные сайты, которые работают! Обслуживаем и эффективно продвигаем интернет-проекты с 2006 года!
Главная Web-мастеру Introduction to GitLab’s CI/CD for Continuous Deployments


Introduction to GitLab’s CI/CD for Continuous Deployments


This article provides a guide to setting up GitLab CI/CD. Earthly ensures consistent and portable build environments for GitLab CI/CD users.

Among the many benefits of GitLab are how it facilitates CI/CD practices, that is continuous integration and continuous deployment. In CI, frequent software updates are immediately tested as they are added to the codebase. In CD, those changes are automatically uploaded to a repository and then deployed to production.

Creating and managing CI/CD pipelines can be difficult, however. GitLab’s CI/CD tools can simplify this process by helping teams manage software builds, testing, and releases with automatic check-ins at each stage to identify and fix any problems in the development cycle.

This tutorial will explore GitLab’s CI/CD tools and offer some use cases for helping you to automate your deployments.

How Does GitLab Enable CI/CD?

Some of the CI/CD practices that developers mostly rely on are continuously adding their code to a shared repository, running automated tests to confirm the build is ready for release, and automatically deploying every change to the production environment.

Deployment pipelines are central to CD, enabling teams to organize their work so that it’s consistently high-quality and allowing them to better control the process. CI/CD practices answer two questions: “Are we building the right things?” and “Are we building things right?”

GitLab is well designed for CI/CD purposes. The single-application DevOps platform aims to streamline your workflow with security scans, quality tests, compliance checks, review/approval processes, and enhanced team collaboration. Here are some use cases for GitLab:

Managing releases: Release management is a vital part of CI/CD as it helps you to keep a record of your source code history, which makes processes more efficient. Each release should have a title, tag name, and description so you can track it.

GitLab takes a snapshot of data when each release is created and saves this data as a JSON file called release evidence, which contains information such as the name, tag name, description, project details, and reports artifact if it has been included in the .gitlab-ci.yml file.

To view release evidence, on the Releases page, click the link to the JSON file that’s listed under the Evidence collection heading.

Automating releases: GitLab’s automated testing reduces the time you spend on each new iteration of your software, while its automated delivery pipelines allow you to deliver your product to the market as quickly and precisely as possible.

Implementing GitLab’s CI/CD Tools

In order to set up GitLab’s CI/CD tools, you need a project in which to implement them. For this tutorial, you need the following:

  • A server where your project will be deployed

  • A repository hosted on GitLab

  • GitLab runner installed on the server

Create a Droplet for Deployment

Create a Droplet on DigitalOcean for deploying your application. This tutorial uses an Ubuntu server on DigitalOcean. Follow these instructions if you don’t already have an existing server.

Create a Non-Root User

After you have created your server, SSH into your server and create a non-root user. You’ll need to pass super admin privileges to the newly created user and log in as the new user, which in this case will be deploying your application. Use this code:

su - <name of non-root user>

Install Dependencies

As the non-root user, you’ll need to install all necessary dependencies for this project to be deployed successfully:

  • Node and npm (run the command sudo apt install nodejs npm)

  • Docker

Create SSH Keys

Now you’ll create an SSH key as a non-root user and copy necessary variables into the GitLab CI/CD variables settings.

To generate the SSH key, enter this command:

ssh-keygen -b 4096

You don’t need to enter a passphrase when asked for one. You might want to save the newly generated keys in the default location so you just need to click Enter.

After the key has been generated, authorize the keys for the current non-root user by using this command:

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Take note of your private key, since you’ll need it later.

Create a Project on GitLab

First, create a project (or use an existing project) and push it to GitLab. You can also create one directly on GitLab.

Go to gitlab.com, log in, and click on the New Project button at the top right section of the Your Projects tab:


New project tab
New project tab


You’ll be taken to the next page to create a project:


Create project page
Create project page


Click on Create Blank Project to initialize a new repository.

You will be redirected to a page where you’ll fill in details like the project name. You can also set the visibility of your project.


Create blank project
Create blank project


Click on Create Project. You can clone the project directly to your computer.

Add Variables To GitLab

You’ll need to save some required variables on your GitLab repository that will enable GitLab to access your server. The variables are:

  • Server username: This is the name of the non-root user
  • Server IP address: This is the IP address of the server
  • SSH keys: This is the private key that was generated on the server by the non-root user

To add these variables, on the left pane of your repository hover on Settings and click on CI/CD. Expand the Variables section and add the keys.

Here is how it should look:


CI/CD Variables
CI/CD Variables


Set Up a GitLab Runner

If you’ve created a new project, you need to register a GitLab Runner, or the agent that will run your code. If you’re using an existing project, you might already have a runner registered. Here’s how to check:

On the right hand of the project dashboard, go to Settings, click on CI/CD, and expand Runners. If there is a runner with a green circle next to it, then you have a runner available.

In order to deploy your application, your runner must be registered on the server by following these instructions.

Make sure to be logged in as a non-root user while doing this.

Code and Test

Now it’s time to write the code needed to be pushed and deployed. For this tutorial, you’ll write a small piece of code for testing to ensure that the CI/CD pipeline works as expected.

Use the entry file of a Node.js application and test the entry point of the application. First, make sure that Express has been installed on the project.

To run the test, you need to have Mocha and Chai installed as dependencies in the project.

In the index.js file of your project setup, copy and paste the code below:

const express = require('express');

        const app = express();
        const port = 3000 || process.env.PORT;
        
        app.get('/', (req, res) => {
            res.status(200).json({ message: 'Hello World of CI/CD' })
        })
        
        app.listen(port, () => {
            console.log(`App started on port ${port}`)
        });
        
        module.exports = app;
        

Create a test.js file and copy and paste the following code into it:

const chai = require("chai");
        const chaiHttp = require("chai-http");
        const { expect } = require("chai");
        const app = require('./index');
        
        chai.use(chaiHttp);
        
        describe('Testing Entry Suite', () => {
            it('Test the entry point', (done) => {
                chai.request(app)
                    .get('/')
                    .set('Accept', 'application/json')
                    .end((err, res) => {
                        expect(res.status).to.have.equal(200);
                        expect(res.body.message).to.be.equal('Hello World of CI/CD');
                        done();
                    });
            });
        });
    

This is a basic test to check that when a user enters the application, hello world is returned along with a status code of 200.

Run this code locally and ensure that it passes.

Create a YAML Configuration File

Create a file named .gitlab-ci.yml in the root of the project folder to define your CI/CD jobs.

When you create this file, it will be detected by GitLab once a push is made.

Below is a snippet of what your .gitlab-ci.yml file should look like:


        image: docker:stable

        cache:
          paths:
            - node_modules/
        
        stages:
          - build
          - deploy
        
        variables:
          TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest
          TAG_COMMIT: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:$CI_COMMIT_SHORT_SHA
        
        build:
          image: docker:latest
          stage: build
          services:
            - docker:dind
          script:
            - echo "Starting to build"
            - docker build -t $TAG_COMMIT -t $TAG_LATEST .
            - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
            - docker push $TAG_COMMIT
            - docker push $TAG_LATEST
        
        deploy:
          image: alpine:latest
          stage: deploy
          script:
            - echo "Starting to deploy"
            - chmod og= $SSH_PRIVATE_KEY
            - apk update && apk add openssh-client
            - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY"
            - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker pull $TAG_COMMIT"
            - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker container rm -f my-project || true"
            - ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker run -d -i -p 3000:3000 --name my-project $TAG_COMMIT"
          environment:
            name: production
            url: http://$SERVER_IP
          only:
            - main
            

Here is a quick overview of how each part works to aid the deployment process:

  • The image defines the Docker image to be used.

  • The cache defines the file or list of files that should be cached between subsequent runs.

  • In the variables section, you’re creating two tags for the Docker image. The TAG_LATEST variable will add the latest tag to the latest built Docker image, while the TAG_COMMIT variable will use the first eight characters of the commit SHA to tag the Docker image.

  • The stages define the order of jobs that would be in the pipeline (note that if no stage is specified, then this defaults to test). Here, there are two stages of the build and deploy as seen above.

The Build Stage Explained

  • The image in this build stage is a Docker image.
  • The stage assigns the current job to build.
  • The service used here is docker:dind, which means Docker-in-Docker. This allows you to use the Docker executor to build your Docker image.
  • The script:
    • Outputs “Starting build” to the console
    
            echo "Starting to build"
        
    • Builds the Docker image using your Dockerfile
    
            docker build -t $TAG_COMMIT -t $TAG_LATEST .
        
    • Logs the Docker image into the project’s container registry
    docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
    • Pushes the image with the variables specified at the top of the file to the container registry
    
            docker push $TAG_COMMIT
        docker push $TAG_LATEST
        

The Deploy Stage

  • The image used at this stage is an Alpine image, which is a minimal Docker image based on Alpine Linux.
  • The stage assigns the current job to deploy.
  • The script:
    • Outputs “Starting to deploy” to the console
    
            echo "Starting to deploy"
        
    • chmod is used to changes access of all other users and groups except for the owner of the file
    
            chmod og= $SSH_PRIVATE_KEY
        
    • The third command of the script updates the Alpine package manager and installs the openssh-client
    
            apk update && apk add openssh-client
        
    • After that, the Docker image is pulled, any existing container with the same name is removed, and the new one is started.
    
            ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY"
        ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker pull $TAG_COMMIT"
        ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker container rm -f my-project || true"
        ssh -i $SSH_PRIVATE_KEY -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "docker run -d -i -p 3000:3000 --name my-project $TAG_COMMIT"
        

Now that you understand the flow of the YAML and Docker files, you need to push your code to your GitLab repository.

Brief Overview of Deployment

When your changes have been pushed, GitLab automatically runs the script in the file created above with the help of the runner that you registered. You can view the pipeline by navigating to the CI/CD panel on GitLab > pipelines.

You should see a list of your pipelines. Click on the topmost pipeline to get more details. Here is how it looks:


Pipeline status
Pipeline status


There are two stages involved in this deployment. The first stage was the build stage; when it was successful, it displayed “Passed” on the status button. While the branch gets merged, the deploy job starts to run, since you stated in the job script to run the deploy stage only when the branch is merged into the main branch.

If your job status is stuck, make sure your runner was properly set up.

Code in Action

Below is a screenshot of the code deployed on an Ubuntu server using DigitalOcean:


Code is Deployed and Running At Digital Ocean!
Code is Deployed and Running At Digital Ocean!


There is another deployment option to consider.

Auto DevOps

This is a collection of pre-configured features and integrations that enables faster software delivery processes. All you need to do is enable Auto DevOps in your project settings. Some of its features include:

  • Auto build
  • Auto test
  • Auto deploy
  • Auto monitoring
  • Providing security

Conclusion

GitLab is well regarded in the software development industry for its fast setup and deployment tools. As this tutorial has demonstrated, GitLab can offer a lot of help in automating your deployment workflow.

Another tool that can help you is Earthly, which allows users to automate all their builds using containers. It integrates with GitLab to provide faster builds and better collaboration among team members. Earthly makes your build self-contained and reproducible, and it ensures that your build can run locally as well as in your CI.

Источник: https://earthly.dev/blog/gitlab-ci/

Introduction to GitLab’s CI/CD for Continuous Deployments | | 2024-04-23 05:12:12 | | Статьи Web-мастеру | | This article provides a guide to setting up GitLab CI/CD. Earthly ensures consistent and portable build environments for GitLab CI/CD users. | РэдЛайн, создание сайта, заказать сайт, разработка сайтов, реклама в Интернете, продвижение, маркетинговые исследования, дизайн студия, веб дизайн, раскрутка сайта, создать сайт компании, сделать сайт, создание сайтов, изготовление сайта, обслуживание сайтов, изготовление сайтов, заказать интернет сайт, создать сайт, изготовить сайт, разработка сайта, web студия, создание веб сайта, поддержка сайта, сайт на заказ, сопровождение сайта, дизайн сайта, сайт под ключ, заказ сайта, реклама сайта, хостинг, регистрация доменов, хабаровск, краснодар, москва, комсомольск |
 
Дайджест новых статей по интернет-маркетингу на ваш email
Подписаться

Продающие сайты "под ключ"!

Наши сайты зарабытывают вам деньги. Landing-page. Эффективные продающие сайты точно в срок и под ключ! Всего от 14700 рублей
Подробнее...

Интернет-магазины и каталоги "под ключ"!

Эффективные и удобные инструменты торговли (электронной торговли) "под ключ". Продают, даже когда вы спите! Всего от 33800 рублей
Подробнее...

Комплексный интернет-маркетинг и продвижение сайтов

Максимальную эффективность дает не какой-то конкретный метод, а их комбинация. Комбинация таких методов и называется комплексным интернет-маркетингом. Всего от 8000 рублей в месяц
Подробнее...

Реклама в Yandex и Google

Контекстная реклама нацелена лишь на тех пользователей, которые непосредственно заинтересованы в рекламе Ваших услуг или товаров. Всего от 8000 рублей в месяц
Подробнее...

Social media marketing (SMM) — продвижение в социальных медиа

Реклама в Однокласcниках и на Mail.ru Создание, ведение и раскрутка групп и реклама ВКонтакте и Facebook. Всего от 8000 рублей в месяц
Подробнее...

Приглашаем к сотрудничеству рекламные агентства и веб-студии!

Внимание Акция! Приглашаем к сотрудничеству рекламные агентства и различные веб-студии России! Индивидуальные и взаимовыгодные условия сотрудничества.
Подробнее...

Ускоренная разработка любого сайта от 5 дней!

Внимание Акция! Ускоренная разработка любого сайта! Ваш сайт будет готов за 5-10 дней. Вы можете заказать разработку любого сайта "под ключ" за 5-10 рабочих дней, с доплатой всего 30% от его стоимости!
Подробнее...

Ждем новых друзей!

Внимание Акция! Ждем новых друзей! Скидка 10% на услуги по созданию и(или) обслуживанию вашего сайта при переходе к нам от другого разработчика.
Подробнее...

Приведи друга и получи скидку!

Внимание Акция! Приведи друга и получи скидку! Скидка 10% на услуги по созданию и(или) обслуживанию вашего сайта, если клиент заказавший наши услуги, пришел по Вашей рекомендации.
Подробнее...

1 2 3 4 5 6 7 8 9

Новые статьи и публикации



Мы создаем сайты, которые работают! Профессионально обслуживаем и продвигаем их , а также по всей России и ближнему зарубежью с 2006 года!

Качественное и объемное представление своего бизнеса в Сети требуется любой растущей коммерческой структуре, стремящейся увеличить продажи, именно по этой причине среди наших клиентов как крупные так и небольшие компании во многих городах России и ближнего зарубежья.
Как мы работаем

Заявка
Позвоните или оставьте заявку на сайте.


Консультация
Обсуждаем что именно Вам нужно и помогаем определить как это лучше сделать!


Договор
Заключаем договор на оказание услуг, в котором прописаны условия и обязанности обеих сторон.


Выполнение работ
Непосредственно оказание требующихся услуг и работ по вашему заданию.


Поддержка
Сдача выполненых работ, последующие корректировки и поддержка при необходимости.

Остались еще вопросы? Просто позвоните и задайте их специалистам
с 2:30 до 11:30 по Мск, звонок бесплатный
Или напишите нам в WhatsApp
с 9:30 до 18:30 по Хабаровску
Или напишите нам в WhatsApp
Веб-студия и агентство комплексного интернет-маркетинга «РЭДЛАЙН» © 2006 - 2024

Профессиональная Веб-разработка. Создание сайтов и магазинов "под ключ" , а также по всей России и зарубежью. Продвижение и реклама. Веб-дизайн. Приложения. Сопровождение. Модернизация. Интеграции. Консалтинг. Продвижение и реклама. Комплексный Интернет-маркетинг.

Оставьте заявку / Задайте вопрос

Нажимая на кнопку ОТПРАВИТЬ, я даю согласие на обработку персональных данных
×

Заказать услугу

Нажимая на кнопку ОТПРАВИТЬ, я даю согласие на обработку персональных данных
×

Обратный звонок

Нажимая на кнопку ОТПРАВИТЬ, я даю согласие на обработку персональных данных
×

Подписка на дайджест новостей

Нажимая на кнопку ОТПРАВИТЬ, я даю согласие на обработку персональных данных
×

Заказать услуги со скидкой \ Бесплатная консультация







КАКИЕ УСЛУГИ ВАС ИНТЕРЕСУЮТ?

КАКИЕ ДОПОЛНИТЕЛЬНЫЕ УСЛУГИ ПОТРЕБУЮТСЯ?

Нажимая на кнопку ОТПРАВИТЬ, я даю согласие на обработку персональных данных
×

Высококачественные сайты по доступным ценамМы создаем практически любые сайты от продающих страниц до сложных, высоконагруженных и нестандартных веб приложений! Наши сайты это надежные маркетинговые инструменты для успеха Вашего бизнеса и увеличения вашей прибыли! Мы делаем красивые и максимально эффектные сайты по доступным ценам уже много лет!

Что нужно сделать, чтобы заказать создание сайта у нас?

Ну для начала вам нужно представлять (хотя бы в общих чертах), что вы хотите получить от сайта и возможно каким вы хотите его видеть. А дальше все просто. Позвоните нам или оставьте заявку нашим менеджерам, чтобы они связались с Вами, проконсультировали и помогли определиться с подходящим именно Вам сайтом по цене, сроку, дизайну или функционалу. Если вы все ещё не уверены, какой сайт вам нужен, просто обратитесь к нам! Мы вместе проанализируем вашу ситуацию и определим максимально эффективный для вас вариант.

Быстрый заказ \ Консультация

Для всех тарифных планов на создание и размещение сайтов включено:

Комплексная раскрутка сайтов и продвижение сайта Комплексный подход это не просто продвижение сайта, это целый комплекс мероприятий, который определяется целями и задачами поставленными перед сайтом и организацией, которая за этим стоит. Время однобоких методов в продвижении сайтов уже прошло, конкуренция слишком высока, чтобы была возможность расслабиться и получать \ удерживать клиентов из Интернета, просто сделав сайт и не занимаясь им...

Комплексная раскрутка работает в рамках стратегии развития вашего бизнеса в сети и направлена

Быстрый заказ \ Консультация

ЭФФЕКТИВНОЕ СОПРОВОЖДЕНИЕ (ПОДДЕРЖКА, ОБСЛУЖИВАНИЕ) САЙТОВ

Полный комплекс услуг по сопровождению сайтаМы оказываем полный комплекс услуг по сопровождению сайта: информационному и техническому обслуживанию и развитию Интернет сайтов.

Передав свой сайт для поддержки в руки наших специалистов, Вы избавитесь от проблем, связанных с обновлением информации и контролем за работой ресурса.

Наша компания осуществляет техническую и информационную поддержку уже имеющихся сайтов. В понятие «поддержка сайтов» также входят услуги администрирования сайтов, обновления сайтов и их модернизация.

Быстрый заказ \ Консультация

Редизайн сайта и Адаптивный веб дизайн

Современный, технологичный, кроссбраузерный ... Профессиональный дизайн сайтов и веб-приложений

Редизайн сайта — создание нового дизайна сайта с целью улучшения внешнего вида, функциональности и удобства использования. Редизайн сайта – это способ преобразовать проект к извлечению из него максимальной отдачи и средств. В современном мире задачами редизайна является поднятие существующего сайта на новый уровень для внедрения новых технологий, при этом сохраняя многолетний сформировавшийся опыт и успешные решения компаний.

Адаптивный дизайн сайтов и веб-приложений

Все больше людей пользуются мобильными устройствами (телефонами, планшетами и прочими) для посещения Интернета, это не для кого уже не новость. Количество таких людей в процентном отношении будет только больше с каждым годом, потому что это удобно и по многим другим причинам.

На сегодняшний день адаптивный дизайн является стандартным подходом при разработке новых сайтов (или веб-приложений) и в идеале ваш сайт должен смотреться и функционировать так, как вы задумывали, на всём разнообразии устройств.

Быстрый заказ \ Консультация

Контекстная реклама в Яндекс и GoogleКонтекстная реклама - это эффективный инструмент в интернет маркетинге, целью которого является увеличение продаж. Главный плюс контекстной рекламы заключается в том, что она работает избирательно.

Реклама в поисковых системах Яндекс и Google. Профессиональная настройка рекламы и отслеживание эффективности!

Рекламные объявления показываются именно тем пользователям, которые ищут информацию о Ваших товарах или услугах, поэтому такая реклама не является навязчивой и раздражающей в отличие от других видов рекламы, с которыми мы сталкиваемся на телевидении или радио. Контекстная реклама нацелена лишь на тех пользователей, которые непосредственно заинтересованы в рекламе Ваших услуг или товаров.

Быстрый заказ \ Консультация

Скидка

1500 руб.
Заинтересовались услугами создания, обслуживания или продвижения вашей компании в Интернете?!
Получите 1500 руб.
за он-лайн заявку
Предложение ограничено.

После получения заявки с Вами свяжутся наши специалисты и уточнят все детали по интересующей вас услуге.
«Нажимая на кнопку "Получить скидку", я даю согласие на обработку персональных данных»
×
Получите 1500 рублей!
×
×