debian

Debian Jenkins与Docker如何结合使用

小樊
47
2025-10-02 04:50:23
栏目: 智能运维

Prerequisites
Before integrating Jenkins with Docker on Debian, ensure the following:

Step 1: Deploy Jenkins in a Docker Container
The most common way to integrate Jenkins with Docker on Debian is to run Jenkins itself inside a Docker container. This provides isolation, portability, and easy management.

Step 2: Configure Jenkins to Use Docker
To allow Jenkins to execute Docker commands (e.g., building, running containers), you need to grant it access to the Docker daemon.

Step 3: Create a Docker-Based Jenkins Pipeline
Use a Jenkinsfile (stored in your source code repository) to define a pipeline that leverages Docker for building, testing, and deploying applications. Below is an example pipeline for a Java application:

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                checkout scm // Pull code from Git
            }
        }
        stage('Build Docker Image') {
            steps {
                script {
                    // Build a Docker image from the current directory (Dockerfile must exist)
                    docker.build("my-app:${env.BUILD_ID}")
                }
            }
        }
        stage('Run Tests in Docker') {
            steps {
                script {
                    // Run tests inside a container created from the built image
                    docker.image("my-app:${env.BUILD_ID}").inside {
                        sh 'mvn test' // Example: Run Maven tests
                    }
                }
            }
        }
        stage('Push to Docker Registry') {
            steps {
                script {
                    // Push the image to Docker Hub (requires credentials)
                    withDockerRegistry([credentialsId: 'docker-hub-creds', url: '']) {
                        sh 'docker push my-app:${env.BUILD_ID}'
                    }
                }
            }
        }
        stage('Deploy to Production') {
            steps {
                script {
                    // Deploy the image to a production server (example: local Docker host)
                    sh 'docker stop my-app || true' // Stop existing container if running
                    sh 'docker rm my-app || true'   // Remove existing container if exists
                    sh 'docker run -d -p 8081:8080 --name my-app my-app:${env.BUILD_ID}'
                }
            }
        }
    }
}

Step 4: Optional - Use Docker Compose for Complex Setups
For applications requiring multiple containers (e.g., a web app + database), use Docker Compose to define and manage the environment.

Best Practices

0
看了该问题的人还看了