Junior
How to deploy on GitLab?
sobes.tech AI
Answer from AI
Deployment in GitLab CI/CD is performed by configuring the .gitlab-ci.yml file in the root directory of the project. This file defines pipelines, stages, and jobs.
The typical deployment process includes:
- Build: Creating artifacts (Docker images, executable files, etc.).
- Testing: Running Unit, Integration, and End-to-End tests.
- Deploy: Deploying artifacts to target environments.
Example of .gitlab-ci.yml for deploying a Docker image:
stages:
- build
- deploy
build:
stage: build
image: docker:latest
services:
- docker:dind
script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
- docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
- docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
deploy_staging:
stage: deploy
image: registry.gitlab.com/gitlab-org/cloud-native/gitlab-agent/agentk/kubectl:latest # Using kubectl
script:
- kubectl config use-context my-kubernetes-context # Switching to the required context
- kubectl apply -f kubernetes/deployment-staging.yaml # Deploy YAML file
environment:
name: staging
only:
- main # Run job only on commits to the main branch
deploy_production:
stage: deploy
image: registry.gitlab.com/gitlab-org/cloud-native/gitlab-agent/agentk/kubectl:latest
script:
- kubectl config use-context my-kubernetes-context
- kubectl apply -f kubernetes/deployment-production.yaml
environment:
name: production
when: manual # Manual job trigger
only:
- main
Key concepts:
- Stages: Define the sequence of job execution.
- Jobs: Specific tasks executed in stages. Can use different Docker images.
- Runners: Agents that execute jobs. Can be shared, specific, or group runners.
- Variables: Used to store sensitive data or configuration. Can be predefined or user-defined (in CI/CD settings).
- Environments: Link deployments to specific environments (staging, production). Facilitate version tracking and rollbacks.
- Rules/Only/Except: Define when a job should run.
Tools for deploying to various platforms include:
| Platform | Tool | Example usage in .gitlab-ci.yml |
|---|---|---|
| Kubernetes | kubectl, Helm | Using images with kubectl or Helm |
| Docker Swarm | docker | Using docker image |
| Cloud Platforms (AWS, GCP, Azure) | AWS CLI, gcloud, az | Using images with respective CLI tools |
| SSH | ssh | Using ssh image and executing commands |
Deployment optimization includes:
- Caching: Speeds up build.
- Parallel job execution: Reduces pipeline time.
- Blue/Green or Canary deployment: To reduce risks.
Sensitive data (passwords, API keys) should be stored in masked CI/CD variables.