溫馨提示×

如何用Debian部署Jenkins CI/CD

小樊
40
2025-09-21 13:44:06
欄目: 智能運維

Prerequisites
Before deploying Jenkins on Debian, ensure your system meets the following requirements:

  • Java Environment: Jenkins requires Java 11 or higher. Install OpenJDK 11 using:
    sudo apt update && sudo apt install -y openjdk-11-jdk
    
    Verify installation with java -version.
  • Debian Version: Use Debian 10 (Buster) or later for compatibility.
  • Disk Space: Allocate at least 10GB for Jenkins home directory (/var/lib/jenkins).
  • Memory: A minimum of 4GB RAM is recommended; 8GB+ is ideal for production.

Step 1: Add Jenkins Repository and Install

  1. Download GPG Key: Import Jenkins’ official GPG key to verify package authenticity:
    wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
    
  2. Add Repository: Create a new source list file for Jenkins and populate it with the stable repository URL:
    echo "deb https://pkg.jenkins.io/debian-stable binary/" | sudo tee /etc/apt/sources.list.d/jenkins.list
    
  3. Update and Install: Refresh the package index and install Jenkins:
    sudo apt update && sudo apt install -y jenkins
    

Step 2: Start and Enable Jenkins Service
Start the Jenkins service and configure it to launch automatically on boot:

sudo systemctl start jenkins
sudo systemctl enable jenkins

Verify the service status with sudo systemctl status jenkins (should show “active (running)”).

Step 3: Unlock Jenkins and Complete Initial Setup

  1. Retrieve Initial Password: The default admin password is stored in a file. Display it using:
    sudo cat /var/lib/jenkins/secrets/initialAdminPassword
    
  2. Access Web Interface: Open a browser and navigate to http://<your_server_ip>:8080. Paste the initial password into the “Unlock Jenkins” prompt.
  3. Install Plugins: Select “Install suggested plugins” to install essential tools (e.g., Pipeline, Git, SSH). Alternatively, manually choose plugins like “Kubernetes” or “Docker” if needed.
  4. Create Admin User: Set up a permanent admin account with a strong username/password and email. This replaces the default “admin” user for security.

Step 4: Configure Global Settings

  1. Tool Configuration: Go to “Manage Jenkins” > “Global Tool Configuration”. Add paths for tools like Java (already installed), Git, and Maven. For example:
    • Git: Set the path to /usr/bin/git (default on Debian).
    • Maven: Click “Add Maven” and specify the installation directory (or enable auto-installation).
  2. Environment Variables: Add global variables (e.g., JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64) under “Manage Jenkins” > “Configure System” to standardize builds across agents.

Step 5: Create a CI/CD Pipeline
Jenkins pipelines automate the entire CI/CD process (build, test, deploy). Use a declarative pipeline (recommended for readability) stored in a Jenkinsfile within your code repository.

  1. Sample Jenkinsfile: Below is a basic pipeline for a Java application using Maven and Git:
    pipeline {
        agent any  // Uses the default Jenkins agent
        environment {
            MAVEN_OPTS = "-Dmaven.test.failure.ignore=true"  // Ignore test failures during build
            ARTIFACT_DIR = "target"
        }
        stages {
            stage('Checkout') {
                steps {
                    git branch: 'main', url: 'https://github.com/your-repo/your-app.git'  // Replace with your repo URL
                }
            }
            stage('Build') {
                steps {
                    sh 'mvn clean package'  // Compile and package the application
                }
            }
            stage('Test') {
                steps {
                    sh 'mvn test'  // Run unit tests
                    junit "${ARTIFACT_DIR}/surefire-reports/*.xml"  // Publish test results
                }
            }
            stage('Deploy to Staging') {
                when { branch 'main' }  // Only deploy from the main branch
                steps {
                    sshagent(['staging-ssh-key']) {  // Use a Jenkins credential for SSH
                        sh 'scp -r ${ARTIFACT_DIR}/* user@staging-server:/opt/app'  // Copy artifacts to staging
                        sh 'ssh user@staging-server "sudo systemctl restart app-service"'  // Restart the app service
                    }
                }
            }
        }
        post {
            always {
                cleanWs()  // Clean up workspace after build
            }
            success {
                slackSend channel: '#ci-cd', message: "Build ${env.BUILD_NUMBER} succeeded!"  // Notify Slack (optional)
            }
            failure {
                mail to: 'team@example.com', subject: "Build ${env.BUILD_NUMBER} Failed", body: "Check console output at ${env.BUILD_URL}"  // Email alert
            }
        }
    }
    
  2. Create Pipeline Job: In Jenkins, click “New Item”, name your job (e.g., “MyApp-CI/CD”), select “Pipeline”, and click OK.
  3. Configure Pipeline:
    • Under “Pipeline”, select “Pipeline script from SCM”.
    • Choose “Git” as the SCM and enter your repository URL.
    • Specify the branch (e.g., main) and the path to the Jenkinsfile (leave blank for root).
  4. Trigger Pipeline: Configure triggers to start builds automatically:
    • Webhook: Add a webhook in your Git provider (e.g., GitHub) pointing to http://<jenkins_url>/github-webhook/. In Jenkins, enable “GitHub hook trigger for GITScm polling”.
    • Poll SCM: Set a schedule (e.g., H/5 * * * * for every 5 minutes) to check for code changes.

Step 6: Secure Jenkins
Security is critical for protecting your CI/CD environment. Implement these measures:

  1. Enable Authentication: Go to “Manage Jenkins” > “Configure Global Security” and enable “Logged-in users can do anything”. Then, install the “Role-based Authorization Strategy” plugin to assign granular permissions (e.g., developers can only build, admins can deploy).
  2. Manage Credentials: Store sensitive data (e.g., SSH keys, API tokens) in Jenkins’ credentials store. Use the “Credentials” section to add credentials and reference them in pipelines with sshagent or withCredentials.
  3. Enable HTTPS: Use Nginx or Apache as a reverse proxy with Let’s Encrypt to secure traffic. Configure HTTPS in Jenkins under “Manage Jenkins” > “Configure Global Security”.
  4. Audit Logs: Install the “Audit Trail” plugin to track user actions (e.g., job modifications, builds) for accountability.

Step 7: Monitor and Optimize

  1. Monitoring: Use plugins like “Monitoring” (by Jenkins) or integrate with Prometheus/Grafana to track resource usage (CPU, memory) and job performance.
  2. Distributed Builds: For large projects, add agent nodes (machines with Jenkins installed) to distribute builds. Configure agents in “Manage Jenkins” > “Manage Nodes and Clouds”.
  3. Performance Tuning: Increase JVM heap size by editing the Jenkins startup script (/etc/default/jenkins) and adding:
    JAVA_OPTS="-Xmx4g -Xms2g"  # Adjust values based on your server’s memory
    
    Restart Jenkins after making changes.

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女