GitLab CI/CD runs automated jobs when code changes or another configured event triggers a pipeline. Common uses include linting, building, testing, packaging, and deployment.
Prerequisites
A GitLab project needs an available GitLab Runner to execute jobs. Depending on your installation, you can use an instance-provided runner or register your own. The executor determines the environment in which each job runs.
Create a pipeline
Add
.gitlab-ci.yml at the repository root:yaml_snippet
YAML · 20 lines|
| stages: |
| - build |
| - test |
| - deploy |
| build: |
| stage: build |
| script: |
| - echo "Build the application" |
| test: |
| stage: test |
| script: |
| - echo "Run tests" |
| deploy: |
| stage: deploy |
| script: |
| - echo "Deploy the application" |
| when: manual |
Jobs in the same stage may run concurrently if runners are available. Later stages normally wait for earlier stages to succeed. Use GitLab's CI Lint before committing to check configuration syntax.
Images and services
With a compatible executor,
image specifies the job's container image and services provides additional containers such as a database. Choose supported, pinned image versions and configure credentials and service readiness for your application. Runner configuration controls available image pull policies.Job setup and execution
before_script runs setup commands before a job's script; after_script can perform cleanup afterward. tags select runners with matching runner tags; these are unrelated to Git tags.Use
rules to decide when jobs run. Older configurations may use only and except; avoid mixing them with rules in the same job. when controls behavior such as manual execution, running on failure, or running regardless of earlier job results.Cache and artifacts
Caches can speed up repeated jobs by reusing suitable dependencies, but a cache hit is not guaranteed. Artifacts preserve job outputs such as build packages or test reports and can be passed to later jobs or downloaded. Configure their paths relative to the project workspace and set a suitable retention period.
Variables and deployment credentials
GitLab provides predefined variables such as
CI_COMMIT_SHA. Define application settings in the pipeline or project settings, and store secrets in protected, appropriately masked CI/CD variables. Restrict protected variables and runners to trusted branches and jobs; masking does not protect a secret from malicious pipeline code.For SSH deployments, use a dedicated least-privilege key and verify the host key using a trusted
known_hosts entry. Do not disable SSH host-key checking. Test deployments and cleanup behavior before enabling automatic production releases.✦ 卷终 · 柯航存卷 ✦